Skip to content

Commit

Permalink
Add Gauge#set_to_current_time
Browse files Browse the repository at this point in the history
I was porting some code from Python to Ruby today, and when I went to
call this method, I realised we don't have it!

My use-case is to track the last time some code successfully ran.

I'm open to discussing the naming, but I've defaulted to the name used
in `client_python` because it seems good to me.

Signed-off-by: Chris Sinjakli <chris@sinjakli.co.uk>
  • Loading branch information
Sinjo committed Jun 9, 2023
1 parent 907b495 commit 1d96723
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/prometheus/client/gauge.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ def set(value, labels: {})
@store.set(labels: label_set_for(labels), val: value)
end

def set_to_current_time(labels: {})
@store.set(labels: label_set_for(labels), val: Time.now.to_f)
end

# Increments Gauge value by 1 or adds the given value to the Gauge.
# (The value can be negative, resulting in a decrease of the Gauge.)
def increment(by: 1, labels: {})
Expand Down
1 change: 1 addition & 0 deletions prometheus-client.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ Gem::Specification.new do |s|

s.add_development_dependency 'benchmark-ips'
s.add_development_dependency 'concurrent-ruby'
s.add_development_dependency 'timecop'
end
24 changes: 24 additions & 0 deletions spec/prometheus/client/gauge_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,30 @@
end
end

describe '#set_to_current_time' do
it 'it sets the gauge to the current Unix epoch time' do
Timecop.freeze(Time.at(12345.1)) do
expect do
gauge.set_to_current_time
end.to change { gauge.get }.from(0).to(12345.1)
end
end

context "with a an expected label set" do
let(:expected_labels) { [:test] }

it 'sets a metric value for a given label set' do
Timecop.freeze(Time.at(12345.1)) do
expect do
expect do
gauge.set_to_current_time(labels: { test: 'value' })
end.to change { gauge.get(labels: { test: 'value' }) }.from(0).to(12345.1)
end.to_not change { gauge.get(labels: { test: 'other' }) }
end
end
end
end

describe '#increment' do
before do
gauge.set(0, labels: RSpec.current_example.metadata[:labels] || {})
Expand Down
3 changes: 3 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# encoding: UTF-8

require 'simplecov'
require 'timecop'

RSpec.configure do |c|
c.warnings = true
Expand All @@ -9,3 +10,5 @@
SimpleCov.formatter = SimpleCov::Formatter::HTMLFormatter

SimpleCov.start

Timecop.safe_mode = true

0 comments on commit 1d96723

Please sign in to comment.