Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Created January 7, 2009 17:11
Show Gist options
  • Save jcoglan/44337 to your computer and use it in GitHub Desktop.
Save jcoglan/44337 to your computer and use it in GitHub Desktop.
# 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