Created
April 24, 2012 17:01
-
-
Save cowboyd/2481494 to your computer and use it in GitHub Desktop.
Injecting an value into a binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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