ander's blog | home | about | atom feed Creative Commons LicenseThis work by Antti Hakala is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 1.0 Finland License.

Concerns in Rails 3

December 14th 2010

A pattern you see around in Rails 3 source code is

module Foo
  extend ActiveSupport::Concern
  # ...
end

Concern

  1. solves a problem of module dependencies piling up on the host, and
  2. provides a pattern for extending the host.

Piling up dependencies becomes a problem when you have a module A and module B, and B uses methods provided by A at include time. Usually, host class C needs to include module A before module B so that needed methods are available at include time, i.e. piling up dependencies.

With ActiveSupport::Concern you can include A to B and just B to host C, cascading dependencies.

module A
  extend ActiveSupport::Concern
  # ...
end

module B
  extend ActiveSupport::Concern
  include A
  
  included do
    # use methods provided by A
  end
end

class C
  include B
end

A concern module has a modified Module#included which can be passed a block to be evaluated. It also automatically extends its ClassMethods module and includes its InstanceMethods module to host, if present.

See also documentation in the source code.

blog comments powered by Disqus