Reputation: 8424
Suppose we have this code:
module A
def n1
puts 'n1'
end
module AA
def n2
puts 'n2'
end
end
end
class B
include A
end
B.new.n1
B.new.n2
The last line will not work unless I do something like include A:AA, or maybe this:
def self.included(base)
base.include AA
end
but are there any other (more convenient) ways to include or reference sub-modules without explicitly including them with :: or inside self.included?
Upvotes: 0
Views: 1110
Reputation: 16514
Redefine the Module
class' :include
method as below, and you be able to include modules recursive:
class Module
alias :include_orig :include
def include mod, options = {}
mod.constants.each do| const |
c = A.const_get const
self.include c, options if c.is_a? Module
end if options[ :recursive ]
self.send :include_orig, mod
end
end
Then call:
class B
include A, :recursive => true
end
B.new.n1
B.new.n2
# n1
# n2
Upvotes: 0
Reputation: 110755
To add methods n1
and n2
in class B
, you could:
include A::AA
to the class definition orinclude AA
in the module A
definition, after the module AA
definition,but it makes more sense to:
module AA
definition out of the module A
definition and add include AA
to the class definition, ormodule AA
before defining module A
and add include AA
to the module A
definition. Upvotes: 1