I am using Ruby 1.9.2 and the Ruby on Rails v3.2.2 gem. I would like to “nest” the inclusion of modules given I am using the RoR ActiveSupport::Concern feature, but I have a doubt where I should state the include method. That is, I have the following:
module MyModuleA
extend ActiveSupport::Concern
# include MyModuleB
included do
# include MyModuleB
end
end
Should I state include MyModuleB in the “body” / “context” / “scope” of MyModuleA or I should state that in the included do ... end block? What is the difference and what I should expect from that?
If you include
MyModuleBin the “body” ofMyModuleA, then it is the module itself that is extended with B’s functionality. If you include it in theincludedblock, then it is included on the class that mixes inMyModuleA.That is:
produces something like:
while
produces something like:
The reason for this is that
ActiveSupport::Concern::includedis analogous to:The code in the
includedblock is run in the context of the including class, rather than the context of the module. Thus, if MyModuleB needs access to the class it’s being mixed-in to, then you’d want to run it in theincludedblock. Otherwise, it’s effectively the same thing.By means of demonstration: