Created
March 6, 2012 22:43
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
module Watchable | |
def events | |
@events ||= Hash.new { |h,k| h[k] = [] } | |
end | |
def fire event, *args | |
events[event].each { |e| e[*args] } | |
end | |
def on event, &block | |
events[event] << block | |
end | |
end |
module Watchable
extend self
def events
@event ||= Hash.new { |h,k| h[k] = [] }
end
def on event, &block
events[event] << block
end
def fire event, *args
events[event].each { |e| e[*args] }
end
def reset!
@event = nil
end
end
require 'minitest/autorun'
describe Watchable do
before do
Watchable.reset!
end
describe '#events' do
it 'must be a hash' do
Watchable.events.must_equal Hash.new
end
it 'must initialize a value to an empty array' do
Watchable.events[:foo].must_equal []
end
end
describe '#on' do
it 'must add a given block to a given key' do
bang = proc { 'bang!' }
Watchable.on :foo, &bang
Watchable.events[:foo].first === bang
end
end
describe '#fire' do
it 'must call all blocks for a given key' do
bang = proc { p 'bang!' }
pow = proc { p 'pow!' }
Watchable.on :foo, &bang
Watchable.on :foo, &pow
out, err = capture_io do
Watchable.fire :foo
end
out.must_match 'bang!'
out.must_match 'pow!'
end
it 'must pass args to block for a given key' do
p_args = proc {|*args| p args }
Watchable.on :foo, &p_args
out, err = capture_io do
Watchable.fire :foo, 'bang!', 'pow!'
end
out.must_match 'bang!'
out.must_match 'pow!'
end
end
end
You could update the gist and use it as a microgem :)
I absolutely could. ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This module should be called
EventEmitter
.