aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/notifications.rb
diff options
context:
space:
mode:
authorXavier Noria <fxn@hashref.com>2011-11-05 12:02:54 -0700
committerXavier Noria <fxn@hashref.com>2011-11-05 12:02:54 -0700
commitd287e90870a9832c9d7e9d222881d3a6102bd04d (patch)
tree821bf391b755f8aaf624e72562674d4414350eb9 /activesupport/lib/active_support/notifications.rb
parentb33232f1b2c3f92c7116adc4b4879a8afc07e70c (diff)
downloadrails-d287e90870a9832c9d7e9d222881d3a6102bd04d.tar.gz
rails-d287e90870a9832c9d7e9d222881d3a6102bd04d.tar.bz2
rails-d287e90870a9832c9d7e9d222881d3a6102bd04d.zip
implements AS::Notifications.subscribed, which provides subscriptions to events while a block runs
Diffstat (limited to 'activesupport/lib/active_support/notifications.rb')
-rw-r--r--activesupport/lib/active_support/notifications.rb41
1 files changed, 41 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb
index 89afe7b982..719f074948 100644
--- a/activesupport/lib/active_support/notifications.rb
+++ b/activesupport/lib/active_support/notifications.rb
@@ -63,6 +63,40 @@ module ActiveSupport
# and even pass no argument to +subscribe+, in which case you are subscribing
# to all events.
#
+ # == Temporary Subscriptions
+ #
+ # Sometimes you do not want to subscribe to an event for the entire life of
+ # the application. There are two ways two unsubscribe.
+ #
+ # === Subscribe While a Block Runs
+ #
+ # You can subscribe to some event temporarily while some block runs. For
+ # example, in
+ #
+ # callback = lambda {|*args| ... }
+ # ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
+ # ...
+ # end
+ #
+ # the callback will be called for all "sql.active_record" events instrumented
+ # during the execution of the block. The callback is unsubscribed automatically
+ # after that.
+ #
+ # === Manual Unsubscription
+ #
+ # The +subscribe+ method returns a subscriber object:
+ #
+ # subscriber = ActiveSupport::Notifications.subscribe("render") do |*args|
+ # ...
+ # end
+ #
+ # To prevent that block from being called anymore, just unsubscribe passing
+ # that reference:
+ #
+ # ActiveSupport::Notifications.unsubscribe(subscriber)
+ #
+ # == Default Queue
+ #
# Notifications ships with a queue implementation that consumes and publish events
# to log subscribers in a thread. You can use any queue implementation you want.
#
@@ -94,6 +128,13 @@ module ActiveSupport
end
end
+ def subscribed(callback, *args, &block)
+ subscriber = subscribe(*args, &callback)
+ yield
+ ensure
+ unsubscribe(subscriber)
+ end
+
def unsubscribe(args)
notifier.unsubscribe(args)
@instrumenters.clear