I am trying to understand the include statement behavior when used in multiple Mixins. That is, I have these statements:
class Article < ActiveRecord::Base
include DoubleIncludedModule
include AModule
# ...
end
module AModule
include DoubleIncludedModule
# ...
end
module DoubleIncludedModule
# ...
end
How many times will be the DoubleIncludedModule included in the Article class? That is, since the “subsequent” inclusion of the DoubleIncludedModule (first in the Article class and then in AModule included by the Article class itself), will be the “double inclusion” issue automatically handled by Ruby or will the DoubleIncludedModule (wrongly) included two times?
Of course, I would like to include the DoubleIncludedModule module only one time. How can I make that (maybe by using some Ruby on Rails methods) the proper way?
I’ll answer with an example:
prints
As we can see,
Ais included only once intoC. Though technically it was included twice since it was included intoBwhich was also included intoC. Does this matter? Probably not. Each still only occurs once in the ancestor chain, and any methods would’ve been overridden with equivalent implementations—i.e., essentially a no-op. Unless you’re doing something exotic with theincludedhook, you’re unlikely to notice anything.