mattly (owner)

Revisions

gist: 102337 Download_button fork
public
Public Clone URL: git://gist.github.com/102337.git
Embed All Files: show embed
task_list.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
task_list_test.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 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