Skip to content
This repository was archived by the owner on Jun 21, 2023. It is now read-only.

stats methods available as class methods on Statsd class #4

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions lib/statsd.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
# statsd = Statsd.new('localhost').tap{|sd| sd.namespace = 'account'}
# statsd.increment 'activate'
class Statsd
class ConfigError < StandardError; end;

# A namespace to prepend to all statsd calls.
attr_accessor :namespace

Expand Down Expand Up @@ -109,4 +111,22 @@ def send_to_socket(message)
end

def socket; @socket ||= UDPSocket.new end

def self.setup(options={})
params = [
options[:host] || "localhost",
options[:port]
].compact
@instance = self.new(*params)
end

def self.clear_setup
@instance = nil
end

def self.method_missing(m, *args, &block)
raise ConfigError.new("I'm not setup()") unless @instance
@instance.__send__(m, *args, &block)
end
end

50 changes: 49 additions & 1 deletion spec/statsd_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,6 @@ def socket; @socket ||= FakeUDPSocket.new end
end

describe "stat names" do

it "should accept anything as stat" do
@statsd.increment(Object, 1)
end
Expand All @@ -176,7 +175,56 @@ class Statsd::SomeClass; end
@statsd.increment('[email protected]|blah.blah:blah', 1)
@statsd.socket.recv.must_equal ['ray_hostname.blah_blah.blah_blah:1|c']
end
end

describe "should support direct calls" do
before do
Statsd.clear_setup
Statsd.setup(:host => "localhost", :port => 1234)
@instance = Statsd.instance_variable_get('@instance')
class << @instance
public :sampled # we need to test this
attr_reader :host, :port # we also need to test this
def socket; @socket ||= FakeUDPSocket.new end
end
end

it 'should complain if setup has not been called' do
Statsd.clear_setup
assert_raises(Statsd::ConfigError) do
Statsd.timing("dummy", rand)
end
end

it 'should setup instance correctly' do
@instance.host.must_equal 'localhost'
@instance.port.must_equal 1234
end

it "should support increment" do
Statsd.increment('foobar')
@instance.socket.recv.must_equal ['foobar:1|c']
end

it "should support decrement" do
Statsd.decrement('foobar')
@instance.socket.recv.must_equal ['foobar:-1|c']
end

it "should support timing" do
t = 100
Statsd.timing('foobar', t)
@instance.socket.recv.must_equal ["foobar:#{t}|ms"]
end

it "should support time" do
Statsd.time('foobar') { sleep(0.001); 'test' }
@instance.socket.recv.must_equal ['foobar:1|ms']
end

it "should support sampled" do
Statsd.sampled(1) { :yielded }.must_equal :yielded
end
end

end
Expand Down