"George Moschovitis" <gm@navel.gr> 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
=> #<MyClass:0x10187e08 @val3="B", @val2="A", @foo="bar", @val1="A",
@val4="B">
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
mod-init.rb (908 Bytes)