I am trying to find a way to get the binding from the caller within method_missing in Ruby (1.8), but I can’t seem to find a way to do it.
Hopefully the following code explains what I would like to do:
class A
def some_method
x = 123
nonexistent_method
end
def method_missing(method, *args, &block)
b = caller_binding # <---- Is this possible?
eval "puts x", b
end
end
A.new.some_method
# expected output:
# 123
So… is there a way to obtain the caller’s binding, or is this just impossible in Ruby (1.8)?
Here’s a (somewhat fragile) hack:
This works with your example, but I haven’t tested it with much else
Of course, this won’t work if the binding doesn’t define the variable you’re trying to evaluate, but this is a general issue with bindings. If a variable is not defined, it doesn’t know what it is.
To get around this, you need to do some error handling within the evaluated string: