Skip to content

Instantly share code, notes, and snippets.

@walski
Forked from cowboyd/inject_this.rb
Created April 24, 2012 17:08
Show Gist options
  • Save walski/2481571 to your computer and use it in GitHub Desktop.
Save walski/2481571 to your computer and use it in GitHub Desktop.
Injecting an value into a binding
def inject_this_as_reference(block, this_object)
block.binding.eval("lambda {|v| @this = v}").call(this_object)
end
def inject_this_as_method(block, this_object)
block.binding.eval('self.singleton_class').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