Skip to content

Instantly share code, notes, and snippets.

@baya
Created December 6, 2011 04:29
Show Gist options
  • Save baya/1436746 to your computer and use it in GitHub Desktop.
Save baya/1436746 to your computer and use it in GitHub Desktop.
ruby blocks as dynamic callbacks
# From http://www.mattsears.com/articles/2011/11/27/ruby-blocks-as-dynamic-callbacks
class Proc
def callback(callable, *args)
self === Class.new do
method_name = callable.to_sym
define_method(method_name) { |&block| block.nil? ? true : block.call(*args) }
define_method("#{method_name}?") { true }
def method_missing(method_name, *args, &block) false; end
end.new
end
end
def tweet(message, &block)
Twitter.update(message)
block.callback :success
rescue => e
block.callback :failure, e.message
end
tweet "Ruby methods with multiple blocks. #lolruby" do |on|
on.success do
puts "Tweet successful!"
end
on.failure do |status|
puts "Error: #{status}"
end
end
tweet "Ruby methods with multiple blocks. #lolruby" do |update|
puts "Tweet successful!" if update.success?
puts "Sorry, something went wrong." if update.failure?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment