Skip to content

Commit

Permalink
Multiple simultaneous subscriptions are go.
Browse files Browse the repository at this point in the history
  • Loading branch information
pdcawley committed Jun 27, 2008
1 parent 6c125af commit 43da3a6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
18 changes: 13 additions & 5 deletions lib/announcer.rb
Expand Up @@ -56,12 +56,20 @@ def initialize
@subscribers = Hash.new {|h,k| h[k] = ActionSequence.new}
end

def subscribe(announcement_class, callable = nil, &block)
unless announcement_class.is_a?(Class) && announcement_class <= Announcement
raise TypeError, "#{announcement_class.inspect} must be an Announcement"
def subscribe(*args, &block)
unless block_given?
callable = args.pop
end

@subscribers[announcement_class] << make_actions(callable || block)
args.each do |each|
unless each.is_a?(Class) && each <= Announcement
raise TypeError, "#{each.inspect} must be an Announcement"
end
end

args.each do |each|
@subscribers[each] << make_actions(callable || block)
end
end

def unsubscribe(context)
Expand All @@ -77,7 +85,7 @@ def unsubscribe_from(*args)
@subscribers[each.to_announcement.class].delete(context)
end
end

def announce(announcement)
unless announcement.respond_to? :to_announcement
raise TypeError, "#{announcement.inspect} must respond to \#to_announcement"
Expand Down
11 changes: 9 additions & 2 deletions spec/ruby_announcements_spec.rb
Expand Up @@ -54,6 +54,13 @@ def target
announcer.announce Announcement
end

it "should allow subscription to multiple announcements" do
target.should_receive(:got).exactly(2).times
announcer.subscribe(AnnouncementMockA, AnnouncementMockB) {|a| target.got(:a)}
announcer.announce AnnouncementMockA
announcer.announce AnnouncementMockB
end

describe 'subscribing with a callable object' do
it "should accept a lambda" do
target.should_receive(:got_announcement).with(duck_type(:Announcement))
Expand All @@ -77,11 +84,11 @@ def target
end

it "should only accept an announcement class as an argument" do
lambda { announcer.subscribe(Object) {} }.should raise_error( TypeError )
lambda { announcer.subscribe(Object) {|| true} }.should raise_error( TypeError )
end

it "should not accept an announcement instance" do
lambda { announcer.subscribe(AnnouncementMockA.new) {} }.should raise_error( TypeError )
lambda { announcer.subscribe(AnnouncementMockA.new) {|| true} }.should raise_error( TypeError )
end
end

Expand Down

0 comments on commit 43da3a6

Please sign in to comment.