From: Sean O'Halpin Date: 2005-10-07T03:02:05+09:00 Subject: Re: techniques for module to contribute to initialize() of its including classes On 10/6/05, ES wrote: > Robert Klemme wrote: > > itsme213 wrote: > > > >>What are good design techniques for this e.g. if the module adds some > >>instance variables to its included class? > >> > >>module M > >> def f > >> @f > >> end > >> # how to initialize @f ? > >>end > >> > >>class A > >> include M > >>end > >>Thanks. > > > > > > Do it like this and the module initialite will seamlessly integrate into > > the class inheritance chain: > > > > module M > > def initialize(*a,&b) > > super > > @f = 10 > > end > > end > > This does not work directly if the class itself defines an #initialize > as it will take precedence over the module version. > It works if you call super from within the class initialize. The module is inserted into the inheritance chain before any superclasses. module M def f @f end # how to initialize @f ? def initialize(*args, &block) puts "in M.initialize" super @f = 10 end end class A def initialize(*args, &block) puts "in A.initialize" super end end class B < A include M def initialize(*args, &block) puts "in B.initialize" super end end b = B.new p b.f __END__ in B.initialize in M.initialize in A.initialize 10 Sean