Initialize() in a module, is it correct?

Hi, for some exotic reason I need to define initialize() method in a
module, so a class including such module can invoke super() in its
initialize() method. It seems to work:


module M
def initialize
puts “I’m module M”
end
end

class A
include M

def initialize
puts “I’m class A instance”
super
end
end

A.new
=> I’m class A instance
=> I’m module M

However I would like to know if there could be an issue by using it. I
do know that constants defined in a module are not accessible from a
class including such module but this is not a problem.

PS: I don’t want to inherit A from other class due to the nature of my
code.

Thanks a lot.

On Mon, Jan 17, 2011 at 6:51 PM, Iaki Baz C. [email protected]
wrote:

=> I’m class A instance
=> I’m module M

However I would like to know if there could be an issue by using it.

I don’t think so. initialize it’s just an instance method, just like
any other, with the same lookup path:

irb(main):001:0> module M
irb(main):002:1> def test; puts “test from M”; end
irb(main):003:1> end
=> nil
irb(main):015:0> class A
irb(main):016:1> include M
irb(main):017:1> def test; puts “test from A”; super; end
irb(main):018:1> end
=> nil
irb(main):019:0> A.new.test
test from A
test from M

Jesus.

El día 17 de enero de 2011 19:08, Jesús Gabriel y Galán
[email protected] escribió:

irb(main):016:1> include M
irb(main):017:1> def test; puts “test from A”; super; end
irb(main):018:1> end
=> nil
irb(main):019:0> A.new.test
test from A
test from M

This is what I expected (and hoped) :slight_smile:

Thanks a lot.

On Mon, Jan 17, 2011 at 7:32 PM, Iaki Baz C. [email protected]
wrote:

=> nil

Thanks a lot.

But you should change the signature to make it more compatible with
arbitrary inheritance chains:

module M
def initialize(*a,&b)
super
puts “I’m module M”
end
end

Now you can use this in different inheritance chains:

class X
def initialize
puts “X”
end
end

class Y < X
include M

def initialize
super
puts “Y”
end
end

class A
def initialize(x)
printf “A(%p)\n”, x
end
end

class B < A
include M

def initialize(a, b)
super(a)
printf “A(%p,%p)\n”, a, b
end
end

B.new 1,2
Y.new

Kind regards

robert