Skip to content

Instantly share code, notes, and snippets.

@jhbabon
Created August 7, 2012 09:44
Show Gist options
  • Save jhbabon/3283959 to your computer and use it in GitHub Desktop.
Save jhbabon/3283959 to your computer and use it in GitHub Desktop.
Block callbacks
# encoding: utf-8
#
# Extract from:
# @link: http://www.mattsears.com/articles/2011/11/27/ruby-blocks-as-dynamic-callbacks
# @link: http://techscursion.com/2011/11/turning-callbacks-inside-out
class ProcCallback
def initialize(callable, *args)
@callable = callable.to_s
@arguments = args.dup
end
def method_missing(method_name, *args, &block)
case method_name.to_s
when @callable, "#{@callable}?"
block_given? ? yield(*@arguments) : true
else
false
end
end
end
Proc.class_eval do
def callback(callable, *args)
call ProcCallback.new(callable, *args)
end
end
def test(&block)
n = rand(2)
if n == 1
block.callback :success
else
block.callback :failure, "FAIL"
end
end
test do |on|
on.success { $stdout.puts "SUCCESS!" }
on.failure { |msg| $stdout.puts "#{msg}!" }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment