Hi, I have a class C that includes a module M.
I need that when a C object is created a module M method is runned
automatically (without call it from "initialize" method) to fill an object
attribute. Something as:
···
---------------------------------------
module M
def module_method
@words << "module_word"
end
end
class C
include C
attr_reader :words
def initialize
@words =
@words << "class_word"
end
end
---------------------------------------
c=C.new
c.words
["class_word", "module_word"]
Is it possible without adding "module_method()" in class C initialize method?
Thanks a lot.
--
Iñaki Baz Castillo
Of course I could use inheritance and super method in "initialize()"
but in fact I need to include more than a module so inheritance
(single using "class < class") is not valid for me.
···
2008/5/1, Iñaki Baz Castillo <ibc@aliax.net>:
> c=C.new
> c.words
["class_word", "module_word"]
Is it possible without adding "module_method()" in class C initialize method?
--
Iñaki Baz Castillo
<ibc@aliax.net>
You can try overwrite initialize method from the module
module M
def self.included(classname)
classname.class_eval <<-EOS
alias_method :old_initialize, :initialize
def initialize
old_initialize
module_method
end
EOS
end
def module_method
@words << "module_word"
end
end
class C
attr_reader :words
def initialize
@words =
@words << "class_word"
end
include M
end
Sandro
www.railsonwave.com
···
On Fri, May 2, 2008 at 7:32 AM, Iñaki Baz Castillo <ibc@aliax.net> wrote:
2008/5/1, Iñaki Baz Castillo <ibc@aliax.net>:
> > c=C.new
> > c.words
> ["class_word", "module_word"]
>
>
> Is it possible without adding "module_method()" in class C initialize method?
Of course I could use inheritance and super method in "initialize()"
but in fact I need to include more than a module so inheritance
(single using "class < class") is not valid for me.
--
Iñaki Baz Castillo
<ibc@aliax.net>
--
Go outside! The graphics are amazing!
Great !!!
I didn't know the meaning of "included" class method of Module. Very
useful in conjunction with "class_eval"

Thanks a lot.
···
2008/5/2, Sandro Paganotti <sandro.paganotti@gmail.com>:
You can try overwrite initialize method from the module
module M
def self.included(classname)
classname.class_eval <<-EOS
alias_method :old_initialize, :initialize
def initialize
old_initialize
module_method
end
EOS
end
def module_method
@words << "module_word"
end
end
class C
attr_reader :words
def initialize
@words =
@words << "class_word"
end
include M
end
--
Iñaki Baz Castillo
<ibc@aliax.net>