I am using Ruby 1.9.2 and the Ruby on Rails v3.2.2 gem. After my previous question on how to “nest” the inclusion of modules when using the Ruby on Rails ActiveSupport::Concern feature, I would like to understand where I should state methods added to a class by including “nested” modules in order to make these instance methods of that class. That is, I have the following:
class MyClass < ActiveRecord::Base
include MyModuleA
end
module MyModuleA
extend ActiveSupport::Concern
included do
include MyModuleB
end
end
module MyModuleB
extend ActiveSupport::Concern
included do
# def my_method
# ...
# end
end
# def my_method
# ...
# end
end
Should I state def my_method ... end in the “body” / “context” / “scope” of MyModuleB or I should state that in the included do ... end block? What is the difference and what I should expect from that?
Methods in modules that get mixed into a class become instance methods on that class. While putting them in the
includedblock would likely work, there’s no need to do it. This, by extension, works with modules, since you can includeModuleBinModuleAand all its instance methods become instance methods onModuleA, and onceModuleAis included on classFoo, all its instance methods (including those mixed in fromB) become instance methods on Foo.A “traditional” mix-in looks like this:
ActiveSupport::Concern just pretties this up a bit by automatically including a module named
ClassMethodsand by running theincludedblock in the context of the including class, so the equivalent is: