Created
January 7, 2009 17:11
-
-
Save jcoglan/44337 to your computer and use it in GitHub Desktop.
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
# Make up for Ruby's odd lack of support for blocks as observers | |
# | |
# class Foo | |
# include Observable::Blocks | |
# end | |
# | |
# f = Foo.new | |
# f.add_observer { puts "f changed" } | |
require 'observer' | |
module Observable | |
module Blocks | |
include Observable | |
class Observer | |
def initialize(&block) | |
@block = block | |
end | |
def update(*args) | |
@block.call(*args) | |
end | |
end | |
def add_observer(*args, &block) | |
if block_given? | |
args[0] = Observer.new(&block) | |
args[1] = :update if args[1] | |
end | |
super(*args) | |
end | |
# Ojay-style message passing | |
def on(message, &block) | |
add_observer do |*args| | |
block.call *([self] + args[1..-1]) if args.first == message | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment