aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/subscriber.rb
diff options
context:
space:
mode:
authorDaniel Schierbeck <dasch@zendesk.com>2013-09-19 11:03:58 +0200
committerDaniel Schierbeck <dasch@zendesk.com>2013-09-20 10:14:28 +0200
commitd2824a347fd827bb0af3c16ffed5a3608b358ffc (patch)
treef30fee6a3f57ebfaf02dfaf81f7f90da50783e21 /activesupport/lib/active_support/subscriber.rb
parent76d36458eadcb32c233f44065fccfbbef9a58119 (diff)
downloadrails-d2824a347fd827bb0af3c16ffed5a3608b358ffc.tar.gz
rails-d2824a347fd827bb0af3c16ffed5a3608b358ffc.tar.bz2
rails-d2824a347fd827bb0af3c16ffed5a3608b358ffc.zip
Allow attaching to AS::Notifications namespace up front
Before, you were required to attach *after* adding the methods to the class, since the attachment process needed the methods to be present. With this change, any new method will also be attached to the configured namespace.
Diffstat (limited to 'activesupport/lib/active_support/subscriber.rb')
-rw-r--r--activesupport/lib/active_support/subscriber.rb27
1 files changed, 25 insertions, 2 deletions
diff --git a/activesupport/lib/active_support/subscriber.rb b/activesupport/lib/active_support/subscriber.rb
index 34c6f900c1..f2966f23fc 100644
--- a/activesupport/lib/active_support/subscriber.rb
+++ b/activesupport/lib/active_support/subscriber.rb
@@ -31,18 +31,41 @@ module ActiveSupport
# Attach the subscriber to a namespace.
def attach_to(namespace, subscriber=new, notifier=ActiveSupport::Notifications)
+ @namespace = namespace
+ @subscriber = subscriber
+ @notifier = notifier
+
subscribers << subscriber
+ # Add event subscribers for all existing methods on the class.
subscriber.public_methods(false).each do |event|
- next if %w{ start finish }.include?(event.to_s)
+ add_event_subscriber(event)
+ end
+ end
- notifier.subscribe("#{event}.#{namespace}", subscriber)
+ # Adds event subscribers for all new methods added to the class.
+ def method_added(event)
+ # Only public methods are added as subscribers, and only if a notifier
+ # has been set up. This means that subscribers will only be set up for
+ # classes that call #attach_to.
+ if public_method_defined?(event) && notifier
+ add_event_subscriber(event)
end
end
def subscribers
@@subscribers ||= []
end
+
+ protected
+
+ attr_reader :subscriber, :notifier, :namespace
+
+ def add_event_subscriber(event)
+ return if %w{ start finish }.include?(event.to_s)
+
+ notifier.subscribe("#{event}.#{namespace}", subscriber)
+ end
end
def initialize