On Wed, 14 Jul 2004, George Moschovitis wrote:

> 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!
>
>
> George Moschovitis
> Navel

if i understand what you are trying to do correctly, you simply need to call
'super' in the appropriate places:

   ~ > cat a.rb
   module M
     def initialize
       super
       p 42
     end
   end
   module M2
     def initialize
       super
       p 42.0
     end
   end
   class C
     include M
     include M2
     def initialize
       super
       p 'forty-two'
     end
   end

   C.new

   ~ > ruby a.rb
   42
   42.0
   "forty-two"

initialize is simply a method so the inclusion of a module which defines it
will cause the currently defined initialize (if there is one) to be
overridden.  so after the 'include M' statement there is one initialize
defined, after the 'include M2' a new one is defined, and finally class C
defines it's own.  if the initialize methods themselves are written in such a
way that they call any previously defined method of the same name (typically
with the same arguments) then they will all effectively be chained together.
in general the pattern for this is:


   def method(*args, &block)

     ret = super(*args, &block)

     # whatever you want to do

     ret

   end


in otherwords, when calling super be sure to pass along any required args and
block and, if you want your new object plug-in where it's superclass would, be
sure to return the expected type(s).

cheers.

-a
--
===============================================================================
| EMAIL   :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
| PHONE   :: 303.497.6469
| A flower falls, even though we love it;
| and a weed grows, even though we do not love it. 
|   --Dogen
===============================================================================