Skip to content

Instantly share code, notes, and snippets.

@mattly
Created April 27, 2009 04:55
Show Gist options
  • Save mattly/102337 to your computer and use it in GitHub Desktop.
Save mattly/102337 to your computer and use it in GitHub Desktop.
module TaskList
def self.included(base)
base.extend Events
base.send :include, Events
end
module Events
def events
@events ||= Hash.new {|h,k| h[k] = []}
end
def task(event, block)
event = event.to_s
events[event] << block
end
end
protected
def fire(event, *args)
(self.class.events[event.to_s] + events[event.to_s]).map {|task| task.call(self, args) }
end
end
# NOTE: this uses a modified version of minitest, don't expect it to run in anything public quite yet
require File.join(File.dirname(__FILE__), '..', 'test_helper.rb')
class TaskListTest
include TaskList
task :foo, lambda {|thing, args| true }
task :bar, lambda {|thing, args| args.first }
task :bar, lambda {|thing, args| thing }
def foo(*args)
fire(:foo, *args)
end
def bar(*args)
fire(:bar, *args)
end
end
describe TaskList do
describe "basics" do
before do
@thing = TaskListTest.new
end
expect { @thing.foo.must_equal [true] }
expect { @thing.foo("bar").must_equal [true] }
expect { @thing.bar("bar").must_equal ["bar", @thing] }
expect { @thing.bar.must_equal [nil, @thing] }
end
describe "with class additions" do
before do
@thing = TaskListTest.new
TaskListTest.task :foo, lambda {|thing,a| thing }
end
expect { @thing.foo.must_equal [true, @thing] }
end
describe "instance addtions" do
before do
@thing = TaskListTest.new
@thing.task :bar, lambda {|thing, args| args.first.capitalize }
end
expect { @thing.bar("bar").must_equal ["bar", @thing, "Bar"]}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment