Skip to content

Commit

Permalink
Support Lambdas as metric names
Browse files Browse the repository at this point in the history
  • Loading branch information
himynameisjonas committed Oct 6, 2012
1 parent 03adcbe commit cb82485
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
8 changes: 4 additions & 4 deletions lib/statsd/instrument.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ module Instrument
def statsd_measure(method, name)
add_to_method(method, name, :measure) do |old_method, new_method, metric_name, *args|
define_method(new_method) do |*args, &block|
StatsD.measure(metric_name) { send(old_method, *args, &block) }
StatsD.measure(metric_name.respond_to?(:call) ? metric_name.call(self) : metric_name) { send(old_method, *args, &block) }
end
end
end
Expand All @@ -47,7 +47,7 @@ def statsd_count_success(method, name)
truthiness = (yield(result) rescue false) if block_given?
result
ensure
StatsD.increment("#{metric_name}." + (truthiness == false ? 'failure' : 'success'))
StatsD.increment("#{metric_name.respond_to?(:call) ? metric_name.call(self) : metric_name}." + (truthiness == false ? 'failure' : 'success'))
end
end
end
Expand All @@ -65,7 +65,7 @@ def statsd_count_if(method, name)
truthiness = (yield(result) rescue false) if block_given?
result
ensure
StatsD.increment(metric_name) if truthiness
StatsD.increment(metric_name.respond_to?(:call) ? metric_name.call(self) : metric_name) if truthiness
end
end
end
Expand All @@ -74,7 +74,7 @@ def statsd_count_if(method, name)
def statsd_count(method, name)
add_to_method(method, name, :count) do |old_method, new_method, metric_name|
define_method(new_method) do |*args, &block|
StatsD.increment(metric_name)
StatsD.increment(metric_name.respond_to?(:call) ? metric_name.call(self) : metric_name)
send(old_method, *args, &block)
end
end
Expand Down
10 changes: 10 additions & 0 deletions test/statsd-instrument_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ def purchase(arg)
end
end

class GatewaySubClass < ActiveMerchant::Gateway
end

ActiveMerchant::Base.extend StatsD::Instrument

class StatsDTest < Test::Unit::TestCase
Expand Down Expand Up @@ -128,6 +131,13 @@ def test_statsd_count
ActiveMerchant::Gateway.new.purchase(true)
end

def test_statsd_count_with_name_as_lambda
ActiveMerchant::Gateway.statsd_count(:ssl_post, lambda {|object| object.class.to_s.downcase + ".insert"})

StatsD.expects(:increment).with('gatewaysubclass.insert')
GatewaySubClass.new.purchase(true)
end

def test_statsd_count_with_method_receiving_block
ActiveMerchant::Base.statsd_count :post_with_block, 'ActiveMerchant.Base.post_with_block'

Expand Down

0 comments on commit cb82485

Please sign in to comment.