Created
August 26, 2008 15:30
-
-
Save jcoglan/7282 to your computer and use it in GitHub Desktop.
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
# Allows methods to be modified so that they accept continuation-passing | |
# style, passing their return value to a block instead of returning it | |
# directly | |
module Continuations | |
METHODS = {} | |
def accept_continuation(*args) | |
args.each do |method_name| | |
func = instance_method(method_name) | |
id = func.object_id | |
METHODS[id] = func | |
module_eval <<-EOS | |
def #{method_name}(*params, &block) | |
value = Continuations::METHODS[#{id}].bind(self).call(*params) | |
block.call(value) if block | |
value | |
end | |
EOS | |
end | |
end | |
end | |
# Example | |
class String | |
extend Continuations | |
accept_continuation :gsub, :downcase | |
end | |
"FOO".downcase do |str| | |
puts str + " !!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment