Module include and class re-opening

Can module2 include module2 and add features to a class from module1?
I tried:

module M1
class A; def f; “f”; end; end
class B; def f; “f”; end; end
end

module M2
include M1
class A; def g; “g”; end; end #don’t want to subclass
end

M2::A.new.g # “g”, as expected
M2::A.new.f # undefined method

M2::b::new.f # “f” as expected

So defining class A in M2 does not 're-open" the included class, but
creates a new class. M1::B, however, comes through fine in M2.

Is it possible
(1) for module M2 to locally modify the definition of M1::A ?
(2) for this modified class to be accessible as M2::A ?

Thanks …

you CAN teach an old dog … wrote:

Can module2 include module2 and add features to a class from module1?
I tried:

module M1
class A; def f; “f”; end; end
class B; def f; “f”; end; end
end

module M2
include M1
class A; def g; “g”; end; end #don’t want to subclass
end

M2::A.new.g # “g”, as expected
M2::A.new.f # undefined method

M2::b::new.f # “f” as expected

So defining class A in M2 does not 're-open" the included class, but
creates a new class. M1::B, however, comes through fine in M2.

Is it possible
(1) for module M2 to locally modify the definition of M1::A ?
(2) for this modified class to be accessible as M2::A ?

Yes, if you cheat a little:

module M2
include M1
M1::A.instance_eval do define_method :g do “G”; end end
end

p M2::A.new.g # “G”
p M2::A.new.f # “f”
p M2::b::new.f # “f”
p M2::A # M1::A

Can module2 include module2 and add features to a class from module1?
Yes, if you cheat a little:

module M2
include M1
M1::A.instance_eval do define_method :g do “G”; end end
end

That’s cheating a lot :slight_smile: The following is a little less evil:

module M1
class A; def f; “f”; end; end
class B; def f; “f”; end; end
end
=> nil
module M2
include M1
TheA = M1::A # could as well do with A
class TheA; def g; “g”; end; end #don’t want to subclass
end
=> nil
M2::A.new.g # “g”, as expected
=> “g”
M2::A.new.f # works
=> “f”
M2::b::new.f # “f” as expected
=> “f”
p M2::TheA
M1::A

But it requires M2 to know about where the classes are coming from, in
case you include several modules (but you normally should, too).

···

On Fri, Jun 13, 2003 at 09:36:59AM +0900, Joel VanderWerf wrote:


_ _

__ __ | | ___ _ __ ___ __ _ _ __
'_ \ / | __/ __| '_ _ \ / ` | ’ \
) | (| | |
__ \ | | | | | (| | | | |
.__/ _,
|_|/| || ||_,|| |_|
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

Those who don’t understand Linux are doomed to reinvent it, poorly.
– unidentified source