Skip to content

Instantly share code, notes, and snippets.

@ryanlecompte
Created December 1, 2011 21:47
Show Gist options
  • Save ryanlecompte/1420133 to your computer and use it in GitHub Desktop.
Save ryanlecompte/1420133 to your computer and use it in GitHub Desktop.
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