From: Michael Neumann Date: 2004-08-18T09:27:39+09:00 Subject: Re: Getting the binding of the caller Florian Gross wrote: > Michael Neumann wrote: > >> Thanks for the quick answer... uhm, but it does seem to behave as it >> should: >> >> require 'binding_of_caller' >> class A >> def m >> Binding.of_caller do |binding| >> eval("self", binding) >> end >> end >> end >> >> p A.new.m # => # >> >> I expect "self" to be "main". > > > That's weird -- can't find an explanation for it, because the following > works: > > require 'binding_of_caller' > this = self > class A > def m > Binding.of_caller do |binding| > eval("this", binding) > end > end > end > > p A.new.m # => main > > Maybe somebody has the knowledge needed to explain what's going on there? Hm, it still doesn't work in my special case, as I get a "Binding.of_caller used in non-method context or trailing statements of method using it aren't in the block." exception (and I really don't understand how this Binding.of_caller really works ;-): require 'binding_of_caller' class Decorator def initialize(&block) @block = block end def >>(meth_id) obj = Binding.of_caller do |binding| eval("this", binding) end old = method(meth_id) new = @block.call(old) # the line below is why I need the Binding.of_caller obj.class.send(:define_method, meth_id, new) end end def wrapwith(value) Decorator.new {|old| proc {|*args| print "##", value, "\n" old.call(*args) } } end wrapwith(42) >> def f(x) x * 2 end p f(4) ############## Regards, Michael