Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Created April 24, 2012 17:01
Show Gist options
  • Save cowboyd/2481494 to your computer and use it in GitHub Desktop.
Save cowboyd/2481494 to your computer and use it in GitHub Desktop.
Injecting an value into a binding
# Is there a better way to inject an arbitrary value into a binding?
def inject_this_as_reference(block, this_object)
eval("lambda {|v| @this = v}", block.binding).call(this_object)
end
def inject_this_as_method(block, this_object)
(class << eval('self', block.binding);self;end).send(:define_method, :this) {this_object}
end
fn = lambda { "this is #{@this}"}
inject_this_as_reference fn, "Radical!" #=> This is Radical!
puts fn.call()
fn = lambda { "this is #{this}"}
inject_this_as_method fn, "Awesome!" #=> This is Awesome!
puts fn.call()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment