Class Binding
In: lib/binding_of_caller.rb
Parent: Object

Methods

of_caller  

Public Class methods

This method returns the binding of the method that called your method. It will raise an Exception when you’re not inside a method.

It’s used like this:

  def inc_counter(amount = 1)
    Binding.of_caller do |binding|
      # Create a lambda that will increase the variable 'counter'
      # in the caller of this method when called.
      inc = eval("lambda { |arg| counter += arg }", binding)
      # We can refer to amount from inside this block safely.
      inc.call(amount)
    end
    # No other statements can go here. Put them inside the block.
  end
  counter = 0
  2.times { inc_counter }
  counter # => 2

Binding.of_caller must be the last statement in the method. This means that you will have to put everything you want to do after the call to Binding.of_caller into the block of it. This should be no problem however, because Ruby has closures. If you don’t do this an Exception will be raised. Because of the way that Binding.of_caller is implemented it has to be done this way.

[Source]

    # File lib/binding_of_caller.rb, line 35
35: def Binding.of_caller(&block)
36:   old_critical = Thread.critical
37:   Thread.critical = true
38:   count = 0
39:   cc, result, error, extra_data = Continuation.create(nil, nil)
40:   error.call if error
41: 
42:   tracer = lambda do |*args|
43:     type, context, extra_data = args[0], args[4], args
44:     if type == "return"
45:       count += 1
46:       # First this method and then calling one will return --
47:       # the trace event of the second event gets the context
48:       # of the method which called the method that called this
49:       # method.
50:       if count == 2
51:         # It would be nice if we could restore the trace_func
52:         # that was set before we swapped in our own one, but
53:         # this is impossible without overloading set_trace_func
54:         # in current Ruby.
55:         set_trace_func(nil)
56:         cc.call(eval("binding", context), nil, extra_data)
57:       end
58:     elsif type == "line" then
59:       nil
60:     elsif type == "c-return" and extra_data[3] == :set_trace_func then
61:       nil
62:     else
63:       set_trace_func(nil)
64:       error_msg = "Binding.of_caller used in non-method context or " +
65:         "trailing statements of method using it aren't in the block."
66:       cc.call(nil, lambda { raise(ArgumentError, error_msg) }, nil)
67:     end
68:   end
69: 
70:   unless result
71:     set_trace_func(tracer)
72:     return nil
73:   else
74:     Thread.critical = old_critical
75:     case block.arity
76:       when 1 then yield(result)
77:       else yield(result, extra_data)        
78:     end
79:   end
80: end

[Validate]