From: Robert Klemme Date: 2004-07-14T20:42:26+09:00 Subject: Re: 'Initializing' modules ------=_NextPart_000_00BC_01C469A7.CC9B6F10 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit "George Moschovitis" schrieb im Newsbeitrag news:cd345h$sdg$1@ulysses.noc.ntua.gr... > Hello everyone, > > I am looking for an elegant solution to a common problem. > Lets say I have 2 modules (A, B): > > module A > attr_accessor :val1 > attr_accessor :val2 > > def initialize > @val1 = @val2 = "A" > end > end > > module B > attr_accessor :val3 > attr_accessor :val4 > > def initialize > @val3 = @val4 = "B" > end > end > > I include the modules in a news class: > > class MyClass > include A, B > > def initialize > # ??? > end > end > > Is there a way to automatically call the initialization code for the two > modules ? Is there a ruby idiom for this? > > Thanks in advance for any help! The Ruby idiom is to use 'super' all over the place: module A attr_accessor :val1 attr_accessor :val2 def initialize(*args) super @val1 = @val2 = "A" end end module B attr_accessor :val3 attr_accessor :val4 def initialize(*args) super @val3 = @val4 = "B" end end class MyClass include A, B def initialize super @foo = "bar" end end => irb(main):028:0> MyClass.new => # Note: to make this work seamless it's best to define initialize(*args) in a module because otherwise there will be problems if you include a module in different classes whose different base classes accept a different amount of arguments. You might want to experiment with the attached script a bit. Regards robert ------=_NextPart_000_00BC_01C469A7.CC9B6F10 Content-Type: application/octet-stream; name="mod-init.rb" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="mod-init.rb" #!/usr/bin/ruby=0A= =0A= class Base1=0A= def initialize=0A= super()=0A= @base1 =3D "base 1"=0A= end=0A= end=0A= =0A= class Base2=0A= def initialize(v)=0A= super()=0A= @base2 =3D v=0A= end=0A= end=0A= =0A= module Mod=0A= def initialize(*args)=0A= super=0A= @mod =3D "Mod"=0A= end=0A= end=0A= =0A= class Der1 < Base1=0A= include Mod=0A= =0A= def initialize=0A= super=0A= @der1 =3D "der 1"=0A= end=0A= end=0A= =0A= class Der2 < Base2=0A= include Mod=0A= =0A= def initialize(v)=0A= super=0A= @der2 =3D v=0A= end=0A= end=0A= =0A= p Der1.ancestors=0A= p Der2.ancestors=0A= =0A= begin=0A= puts "creating Der1"=0A= Der1.new=0A= rescue Exception =3D> e=0A= p e=0A= puts e.backtrace=0A= end=0A= =0A= begin=0A= puts "creating Der2"=0A= Der2.new "der 2"=0A= rescue Exception =3D> e=0A= p e=0A= puts e.backtrace=0A= end=0A= =0A= module Mod=0A= def initialize(*args)=0A= super()=0A= @mod =3D "Mod"=0A= end=0A= end=0A= =0A= begin=0A= puts "creating Der1"=0A= Der1.new=0A= rescue Exception =3D> e=0A= p e=0A= puts e.backtrace=0A= end=0A= =0A= begin=0A= puts "creating Der2"=0A= Der2.new "der 2"=0A= rescue Exception =3D> e=0A= p e=0A= puts e.backtrace=0A= end=0A= ------=_NextPart_000_00BC_01C469A7.CC9B6F10--