Guest User

Untitled

a guest
Feb 19th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. # Allows methods to be modified so that they accept continuation-passing
  2. # style, passing their return value to a block instead of returning it
  3. # directly
  4.  
  5. module Continuations
  6. METHODS = {}
  7.  
  8. def accept_continuation(*args)
  9. args.each do |method_name|
  10. func = instance_method(method_name)
  11. id = func.object_id
  12. METHODS[id] = func
  13.  
  14. module_eval <<-EOS
  15. def #{method_name}(*params, &block)
  16. value = Continuations::METHODS[#{id}].bind(self).call(*params)
  17. block.call(value) if block
  18. value
  19. end
  20. EOS
  21. end
  22. end
  23. end
  24.  
  25.  
  26. # Example
  27.  
  28. class String
  29. extend Continuations
  30. accept_continuation :gsub, :downcase
  31. end
  32.  
  33. "FOO".downcase do |str|
  34. puts str + " !!"
  35. end
Add Comment
Please, Sign In to add comment