/binding_of_caller

Obtain a caller’s binding in MRI Ruby 1.9.2.

Primary LanguageRuby

binding_of_caller

Summary

Obtain a caller’s binding in MRI Ruby 1.9.3+.

Synopsis

def f
  x = 33
  g
end

def g
  BindingOfCaller.binding_of_caller do |bind|
    eval("x", bind)
  end
end

p f  # => 33

Description

Obtain a caller’s binding in MRI Ruby 1.9.3 or higher through the use of a continuation.

Restrictions

(1) Statements cannot appear after the binding_of_caller block.

def f
  x = 33
  g
end

def g
  BindingOfCaller.binding_of_caller do |bind|
    eval("x", bind)
  end
  puts "hello"  # <-- error
end

(2) The method using binding_of_caller cannot appear inside a method call.

def f
  x = 33
  run(g)  # <-- error
end

def h
  x = 33
  result = g  
  run(result)  # OK
end

def g
  BindingOfCaller.binding_of_caller do |bind|
    eval("x", bind)
  end
end

(3) The method using binding_of_caller cannot be called from the last line of a block or global scope.

def f
  1.times do
    x = 33
    g  # <-- error: last line of block
  end
end

def h
  1.times do
    x = 33
    g  # <-- OK
    nil
  end
end

def g
  BindingOfCaller.binding_of_caller do |bind|
    eval("x", bind)
  end
end

Author

  • James M. Lawrence < quixoticsycophant@gmail.com >

License

Copyright (c) 2011 James M. Lawrence. All rights reserved.

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.