Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Alternative to modifying Proc directly
# 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