Skip to content

Instantly share code, notes, and snippets.

@groesser3
Created December 12, 2011 05:37
Show Gist options
  • Save groesser3/1465188 to your computer and use it in GitHub Desktop.
Save groesser3/1465188 to your computer and use it in GitHub Desktop.
multiple blocks
# by Matt Sears
# 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
class Twitter
def self.update(message)
puts message
#raise "Fail Wale!"
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
# inspired by
# http://www.mattsears.com/articles/2011/11/27/ruby-blocks-as-dynamic-callbacks
module Twitter
class Twitter
def method_missing(method, *args, &block)
method_name = method.to_sym
define_singleton_method(method_name) do |*args, &b|
block.nil? ? true : block.call(*args, &b)
end
end
def update(message)
puts message
# raise "Fail!"
end
def do_tweet(message, &block)
block.call(self) # !!!
begin
update(message)
success
rescue => e
failure(e.message)
end
end
end
def tweet(*args, &block)
Twitter.new.do_tweet(args, &block)
end
end
include Twitter
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment