Created
December 12, 2011 05:37
-
-
Save groesser3/1465188 to your computer and use it in GitHub Desktop.
multiple blocks
This file contains hidden or 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
# 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 | |
This file contains hidden or 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
# 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