How to exec a module method when "include Module" from a Class?

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

irb> c=C.new
irb> c.words
[“class_word”, “module_word”]

Is it possible without adding “module_method()” in class C initialize
method?

Thanks a lot.

2008/5/1, Iñaki Baz C. [email protected]:

irb> c=C.new
irb> 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.

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

2008/5/2, Sandro P. [email protected]:

     end

class C
include M
end

Great !!!
I didn’t know the meaning of “included” class method of Module. Very
useful in conjunction with “class_eval”
:slight_smile:

Thanks a lot.