How a Ruby class to initialize all included modules? -
see following sample code first:
module first   def initialize     puts "second init"   end    def first     puts "first"   end end  module second   def initialize     puts "second init"   end    def second     puts "second"   end end  class myclass   include first   include second    def initialize     super()   end end  c = myclass.new c.first c.second   output of program is:
second init first second   from output, can see myclass has included first , second modules, because has both first() , second() methods.
in myclass constructor, try initialize both included modules super(), seems second's constructor called.
how initialize included modules?
include inserts module in between present class , ancestors. since first, second included, ancestors of myclass is
[myclass, second, first, ...]   the keyword super looks first method available in ancestor class besides own class. , finds second#initialize.
if want accumulate initialize methods of ancestor modules, this:
module first   def initialize     puts "second init"   end end  module second   include first   def initialize     super     puts "second init"   end end  class myclass   include second   def initialize     super   end end      
Comments
Post a Comment