Using ActiveSupport::Concern for easy mix-ins…

August 20, 2010 Mike Gehard

If you are writing you own mix-in modules in Rails3 and haven’t taken a look at ActiveSupport::Concern yet, I recommend checking out this blog posting for an outline of why you should be using it:

If you are already using this then good for you and you can continue on.

Here’s a little “stumbling block” with ActiveSupport::Concern that I found the other day that I wanted to share with people. If you have the following code:

module Bar
  extend ActiveSupport::Concern

  included do
    attr_accessor :baz

  def baz

class Foo
  include Bar


You might expect the puts to write out “Baz” but it writes out nil instead. Why is that? It has to do with the order in which ActiveSupport::Concern tacks all of the module code into the class including the module. If you
change “attr_accessor” to attr_writer” all works as planned.

So yes you might be saying “why do you have attr_accessor when you define a getter method for baz?” and my response is “because it worked ok before I factored the code out into a module for reuse”.

About the Author


Adding Routes for tests / specs with Rails 3
Adding Routes for tests / specs with Rails 3

If you ever need to test an abstract base controller independently from any subclass, you'll likely need to...

JavaScript constructors, prototypes, and the `new` keyword
JavaScript constructors, prototypes, and the `new` keyword

Are you baffled by the new operator in JavaScript? Wonder what the difference between a function and a con...

SpringOne 2021

Register Now