Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Implement methodphitamine-based chaining for event handlers.

  • Loading branch information...
commit e48e9bcae01492eac46fbc5843525941f9210642 1 parent d542a5d
@jcoglan authored
Showing with 36 additions and 4 deletions.
  1. +1 −0  Rakefile
  2. +14 −3 lib/eventful.rb
  3. +21 −1 test/test_eventful.rb
View
1  Rakefile
@@ -6,6 +6,7 @@ require 'hoe'
Hoe.spec 'eventful' do |p|
# self.rubyforge_name = 'eventfulx' # if different than 'eventful'
p.developer('James Coglan', 'jcoglan@googlemail.com')
+ p.extra_deps = %w[methodphitamine]
end
# vim: syntax=ruby
View
17 lib/eventful.rb
@@ -1,16 +1,24 @@
require 'observer'
+require 'rubygems'
+require 'methodphitamine'
module Eventful
VERSION = '0.9.0'
- class Observer
+ class Observer < Methodphitamine::It
def initialize(&block)
+ super()
@block = block
end
def update(*args)
@block.call(*args)
end
+
+ # Patch this back in after Methodphitamine removes it
+ def respond_to?(*args)
+ Object.instance_method(:respond_to?).bind(self).call(*args)
+ end
end
module ObservableWithBlocks
@@ -27,9 +35,12 @@ def add_observer(*args, &block)
include ObservableWithBlocks
def on(event, &block)
- add_observer do |*args|
+ observer = add_observer do |*args|
type, data = args.first, [self] + args[1..-1]
- block.call(*data) if type == event
+ if type == event
+ block ||= observer.to_proc
+ block.call(*data)
+ end
end
end
View
22 test/test_eventful.rb
@@ -3,10 +3,19 @@
class Foo
include Eventful
+ attr_reader :count
+
+ def initialize
+ @count = 0
+ end
+
+ def bump!(x = 1)
+ @count += x
+ end
end
class TestEventful < Test::Unit::TestCase
- def test_sanity
+ def test_named_events
ayes, noes = 0, 0
f = Foo.new
f.on(:aye) { |foo, x| ayes += x }
@@ -24,4 +33,15 @@ def test_sanity
assert_equal 1, ayes
assert_equal 3, noes
end
+
+ def test_chaining
+ f = Foo.new
+ f.on(:aye).bump! 2
+ f.on(:noe).bump! -1
+
+ 2.times { f.fire(:aye) }
+ f.fire(:noe)
+
+ assert_equal 3, f.count
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.