I had no idea that extend has an append_features-style callback, you
learn something every day. Thanks Mauricio.
i think you should elaborate on what you really want, what mauricio posted,
though cool, definitely modifies the class:
harp:~ > cat a.rb
module N
class << self; attr_accessor :bleh end # just to prove #foo was run
self.bleh = "#foo not executed"
def foo
N.bleh = "#foo was executed!!"
end
end
module M
def self.extend_object(o)
o.class_eval do
include N
def self.new(*a,&b)
r = super(*a, &b) # explicit -> less stuff to remember
r.foo # is this what you meant?? weird.
# why won't X.new.foo do?
r
end
end
end
end
# ===== unmodified =>
class X
p ancestors
extend M
p ancestors
end
harp:~ > ruby a.rb
[X, Object, Kernel]
[X, N, Object, Kernel]
what, exactly do you mean when you say the class must not be modified? both
the solution i posted and this one modify the class in exactly the same way :
by including a module in the class.
what you originally posted:
given the below, if you were not allowed to modify class X
module N
def foo
end
end
module M
# ...
end
class X
extend M
end
would it possible for
x = X.new
to somehow call foo as an instance method of x?
iff you really do not modify the class X, can be accomplished thus:
harp:~ > cat a.rb
module N
def foo() p 42 end
end
module M
include N
end
class X; end
x = X.new
x.extend M
x.foo
harp:~ > ruby a.rb
42
any other way to be able to call x.foo will, in fact, modify the class X. but
maybe that's not what you really want?
regards.
-a
···
On Thu, 4 May 2006, Mike Harris wrote:
--
be kind whenever possible... it is always possible.
- h.h. the 14th dali lama