Last active
December 23, 2015 12:39
-
-
Save luxerama/6636289 to your computer and use it in GitHub Desktop.
Dynamic Ruby callbacks, from http://www.mattsears.com/articles/2011/11/27/ruby-blocks-as-dynamic-callbacks
This file contains 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
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 |
This file contains 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
publish "some content" do |receiver| | |
receiver.success do | |
puts 'published' | |
end | |
receiver.failure do |failure| | |
puts "not published because #{failure}" | |
end | |
end |
This file contains 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
def publish(content, &block) | |
display content | |
block.callback :success | |
rescue => e | |
block.callback :failure, e.message | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment