ActiveSupport::Concern

ActiveSupport::Concern encapsulates the include-and-extend trick and fixes the problem of chained inclusions. A module can get this functionality by extending Concern and defining its own ClassMethods module:

 require ​'active_support'
 
 module​ MyConcern
 extend​ ActiveSupport::Concern
 
 def​ an_instance_method; ​"an instance method"​; ​end
 
 module​ ClassMethods
 def​ a_class_method; ​"a class method"​; ​end
 end
 end
 
 class​ MyClass
 include​ MyConcern
 end
 
 MyClass.new.an_instance_method ​# => "an instance method"
 MyClass.a_class_method ​# => "a class method"

In the rest of this chapter I’ll use the word “concern” with a lowercase C to mean “a module that extend ...

Get Metaprogramming Ruby 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.