From 2c4b97cc80f9df7488299ea9d254bf64227ab70e Mon Sep 17 00:00:00 2001 From: Evan Chan Date: Thu, 10 May 2012 13:51:44 -0700 Subject: [PATCH] Fix gauge so block can reference vars in its own class context --- lib/ruby-metrics/instruments/gauge.rb | 2 +- spec/instruments/gauge_spec.rb | 44 ++++++++++++++++++++------- 2 files changed, 34 insertions(+), 12 deletions(-) diff --git a/lib/ruby-metrics/instruments/gauge.rb b/lib/ruby-metrics/instruments/gauge.rb index d4f8cee..8d03c55 100644 --- a/lib/ruby-metrics/instruments/gauge.rb +++ b/lib/ruby-metrics/instruments/gauge.rb @@ -7,7 +7,7 @@ def initialize(&block) end def get - instance_exec(&@block) + @block.call end def as_json(*_) diff --git a/spec/instruments/gauge_spec.rb b/spec/instruments/gauge_spec.rb index 81cade9..3f818e1 100644 --- a/spec/instruments/gauge_spec.rb +++ b/spec/instruments/gauge_spec.rb @@ -8,35 +8,57 @@ callback = Proc.new {} @gauge = Metrics::Instruments::Gauge.new &callback end - + it "should correctly callback the block given when we call Gauge#get" do result = 42 - - callback = Proc.new do + + callback = Proc.new do { :result => result } end - + @gauge = Metrics::Instruments::Gauge.new &callback - + @gauge.get[:result].should == 42 - + result += 1 - + @gauge.get[:result].should == 43 end - + + class Test + def initialize + @gauge = Metrics::Instruments::Gauge.new { @status.to_s } + @status = :new + end + + def change_status + @status = :old + end + + def get_gauge + @gauge.get + end + end + + it "gauge block within another class should be able to reference other classes variables" do + test_class = Test.new + test_class.get_gauge.should == "new" + test_class.change_status + test_class.get_gauge.should == "old" + end + context "to_json" do it "should serialize the current value" do result = 0 gauge = Metrics::Instruments::Gauge.new{ result } - + gauge.to_json.should == result.to_s - + result = 2 gauge.to_json.should == result.to_s end end - + end