Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial basic functionality for named events.

  • Loading branch information...
commit d542a5db13eb87bd668ad15fed7d1e43380f3d8d 1 parent 2046082
@jcoglan authored
Showing with 62 additions and 2 deletions.
  1. +42 −1 lib/eventful.rb
  2. +20 −1 test/test_eventful.rb
View
43 lib/eventful.rb
@@ -1,3 +1,44 @@
-class Eventful
+require 'observer'
+
+module Eventful
VERSION = '0.9.0'
+
+ class Observer
+ def initialize(&block)
+ @block = block
+ end
+
+ def update(*args)
+ @block.call(*args)
+ end
+ end
+
+ module ObservableWithBlocks
+ include Observable
+
+ def add_observer(*args, &block)
+ return super unless block_given?
+ observer = Observer.new(&block)
+ add_observer(observer)
+ observer
+ end
+ end
+
+ include ObservableWithBlocks
+
+ def on(event, &block)
+ add_observer do |*args|
+ type, data = args.first, [self] + args[1..-1]
+ block.call(*data) if type == event
+ end
+ end
+
+ def fire(*args)
+ return if defined?(@observer_state) and not @observer_state
+ changed(true)
+ notify_observers(*args)
+ changed(true)
+ end
+
end
+
View
21 test/test_eventful.rb
@@ -1,8 +1,27 @@
require "test/unit"
require "eventful"
+class Foo
+ include Eventful
+end
+
class TestEventful < Test::Unit::TestCase
def test_sanity
- flunk "write tests or I will kneecap you"
+ ayes, noes = 0, 0
+ f = Foo.new
+ f.on(:aye) { |foo, x| ayes += x }
+ obs = f.on(:noe) { |foo, x| noes += x }
+
+ f.fire(:aye, 1)
+ assert_equal 1, ayes
+ assert_equal 0, noes
+ f.fire(:noe, 3)
+ assert_equal 1, ayes
+ assert_equal 3, noes
+
+ f.delete_observer(obs)
+ f.fire(:noe, 3)
+ assert_equal 1, ayes
+ assert_equal 3, noes
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.