Skip to content

Instantly share code, notes, and snippets.

@lcowell
Created February 3, 2012 05:33
Show Gist options
  • Save lcowell/1728345 to your computer and use it in GitHub Desktop.
Save lcowell/1728345 to your computer and use it in GitHub Desktop.
avoiding included {} with ActiveSupport::Concern

We can call a class macro on an instance of a class like this:

class Foo attr_accessor :bar end

Foo.new.bar = 1

We can call a class macro on the class in this way:

class Person class << self attr_accessor :name end end

Person.name = "Luke"

Let's say we want to have this happen automatically when we include a module. In the following example, as klass is equal to self in the declaration above "class << self", we can apply the same technique we used above.

module Age def self.included(klass) class << klass attr_accessor :age end end end

If we'd included that module in to Person, we could then do:

Person.age = "old enough to know better"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment