Skip to content

Commit

Permalink
Add instrument! to notifications which adds the result to the payload.
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Jan 14, 2010
1 parent 2a6bc12 commit 7c3573f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
2 changes: 1 addition & 1 deletion activesupport/lib/active_support/notifications.rb
Expand Up @@ -45,7 +45,7 @@ module Notifications
class << self
attr_writer :notifier
delegate :publish, :subscribe, :to => :notifier
delegate :instrument, :to => :instrumenter
delegate :instrument, :instrument!, :to => :instrumenter

def notifier
@notifier ||= Notifier.new
Expand Down
10 changes: 9 additions & 1 deletion activesupport/lib/active_support/notifications/instrumenter.rb
Expand Up @@ -11,13 +11,21 @@ def initialize(notifier)
@notifier = notifier
end

def instrument(name, payload={})
# Instrument the given block by measuring the time taken to execute it
# and publish it.
def instrument(name, payload={}, add_result=false)
time = Time.now
result = yield if block_given?
payload.merge!(:result => result) if add_result
@notifier.publish(name, time, Time.now, @id, payload)
result
end

# The same as instrument, but adds the result as payload.
def instrument!(name, payload={}, &block)
instrument(name, payload, true, &block)
end

private
def unique_id
SecureRandom.hex(10)
Expand Down
12 changes: 11 additions & 1 deletion activesupport/test/notifications_test.rb
Expand Up @@ -83,10 +83,20 @@ def setup
end

class InstrumentationTest < TestCase
delegate :instrument, :to => ActiveSupport::Notifications
delegate :instrument, :instrument!, :to => ActiveSupport::Notifications

def test_instrument_returns_block_result
assert_equal 2, instrument(:awesome) { 1 + 1 }
drain
end

def test_instrument_with_band_adds_result_to_payload
assert_equal 2, instrument!(:awesome) { 1 + 1 }
drain

assert_equal 1, @events.size
assert_equal :awesome, @events.first.name
assert_equal Hash[:result => 2], @events.first.payload
end

def test_instrumenter_exposes_its_id
Expand Down

0 comments on commit 7c3573f

Please sign in to comment.