daremkd
daremkd

Reputation: 8424

Alternative ways to include sub-modules into classes in Ruby

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

Answers (2)

Малъ Скрылевъ
Малъ Скрылевъ

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

Cary Swoveland
Cary Swoveland

Reputation: 110755

To add methods n1 and n2 in class B, you could:

  • add include A::AA to the class definition or
  • add include AA in the module A definition, after the module AA definition,

but it makes more sense to:

  • move the module AA definition out of the module A definition and add include AA to the class definition, or
  • define module AA before defining module A and add include AA to the module A definition.

Upvotes: 1

Related Questions