Created
December 1, 2011 21:47
-
-
Save ryanlecompte/1420133 to your computer and use it in GitHub Desktop.
Alternative to modifying Proc directly
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
# alternative to what is explained in the article Ruby Blocks as Dynamic Callbacks: | |
# http://www.mattsears.com/articles/2011/11/27/ruby-blocks-as-dynamic-callbacks | |
class Twitter | |
def tweet(msg, &block) | |
proxy = DSL[block] | |
publish(msg) | |
proxy.respond_with(:success) | |
rescue => e | |
proxy.respond_with(:failure, e.message) | |
end | |
class DSL | |
def self.[](block) | |
new.tap { |proxy| block.call(proxy) } | |
end | |
def respond_with(callback, *args) | |
callbacks[callback].call(*args) | |
end | |
def method_missing(m, *args, &block) | |
block ? callbacks[m] = block : super | |
self | |
end | |
private | |
def callbacks | |
@callbacks ||= {} | |
end | |
end | |
end | |
t = Twitter.new | |
t.tweet('Hello there!') do |on| | |
on.success do | |
puts "Success!" | |
end | |
on.failure do |msg| | |
puts "Failure! Message: #{msg}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment