Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
allow unsubscribe by name or subscription [#4433 state:resolved]
Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information
dchelimsky authored and jeremy committed Apr 25, 2010
1 parent df886c4 commit 864bd9c
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
1 change: 1 addition & 0 deletions actionpack/lib/action_controller/test_case.rb
Expand Up @@ -36,6 +36,7 @@ def setup_subscriptions
end

def teardown_subscriptions
ActiveSupport::Notifications.unsubscribe("action_view.render_template")
ActiveSupport::Notifications.unsubscribe("action_view.render_template!")
end

Expand Down
20 changes: 15 additions & 5 deletions activesupport/lib/active_support/notifications/fanout.rb
Expand Up @@ -19,8 +19,8 @@ def subscribe(pattern = nil, &block)
end

def unsubscribe(subscriber)
@subscribers.delete(subscriber)
@listeners_for.clear
@subscribers.reject! {|s| s.matches?(subscriber)}
end

def publish(name, *args)
Expand Down Expand Up @@ -60,7 +60,7 @@ def initialize(pattern, &block)
end

def publish(*args)
return unless matches?(args.first)
return unless subscribed_to?(args.first)
push(*args)
true
end
Expand All @@ -69,10 +69,20 @@ def drained?
true
end

private
def matches?(name)
!@pattern || @pattern =~ name.to_s
def subscribed_to?(name)
!@pattern || @pattern =~ name.to_s
end

def matches?(subscriber_or_name)
case subscriber_or_name
when String
@pattern && @pattern =~ subscriber_or_name
when self
true
end
end

private

def push(*args)
@block.call(*args)
Expand Down
22 changes: 22 additions & 0 deletions activesupport/test/notifications_test.rb
Expand Up @@ -6,7 +6,9 @@ def setup
ActiveSupport::Notifications.notifier = nil
@notifier = ActiveSupport::Notifications.notifier
@events = []
@named_events = []
@subscription = @notifier.subscribe { |*args| @events << event(*args) }
@named_subscription = @notifier.subscribe("named.subscription") { |*args| @named_events << event(*args) }
end

private
Expand All @@ -30,6 +32,26 @@ def test_unsubscribing_removes_a_subscription
assert_equal [[:foo]], @events
end

def test_unsubscribing_by_name_removes_a_subscription
@notifier.publish "named.subscription", :foo
@notifier.wait
assert_equal [["named.subscription", :foo]], @named_events
@notifier.unsubscribe("named.subscription")
@notifier.publish "named.subscription", :foo
@notifier.wait
assert_equal [["named.subscription", :foo]], @named_events
end

def test_unsubscribing_by_name_leaves_the_other_subscriptions
@notifier.publish "named.subscription", :foo
@notifier.wait
assert_equal [["named.subscription", :foo]], @events
@notifier.unsubscribe("named.subscription")
@notifier.publish "named.subscription", :foo
@notifier.wait
assert_equal [["named.subscription", :foo], ["named.subscription", :foo]], @events
end

private
def event(*args)
args
Expand Down

0 comments on commit 864bd9c

Please sign in to comment.