Andreas Launila
6/11/2007 9:01:00 PM
Joel VanderWerf wrote:
> It doesn't seem possible to use const_missing to do this, because
> const_missing is called on Foo (not on the instance or the singleton
> class) and there is no way to identify the instance of Foo in the
> const_missing method.
>
I didn't know that const_missing existed, that might be just enough to
not have to redefine constants if one accepts some dirtiness. Here is an
adaptation of your code with that thrown in.
class Object
def singleton_class
class << self; self; end
end
end
class Foo
def foo
p BAR
end
private
def self.const_missing(name)
if !@caller.nil? and @caller.singleton_class.const_defined? name
@caller.singleton_class.const_get(name)
else
super
end
end
def self.next_caller(caller)
@caller = caller
end
end
f = Foo.new
class <<f
BAR = "Hello"
alias_method :old_foo, :foo
def foo
self.class.next_caller(self)
old_foo
self.class.next_caller(nil)
end
end
g = Foo.new
class <<g
BAR = "Goodbye"
alias_method :old_foo, :foo
def foo
self.class.next_caller(self)
old_foo
self.class.next_caller(nil)
end
end
f.foo
g.foo
f.foo
Outputs
"Hello"
"Goodbye"
"Hello"
It isn't pretty, it isn't thread safe, it will not work if Foo is called
directly, it could be shortened/generalized/altered/improved depending
on the purpose.
Thank you :)
--
Andreas Launila