Skip to content

Commit 7507716

Browse files
authored
Merge pull request #287 from prometheus/sinjo-add-gauge-current-timestamp
Add `Gauge#set_to_current_time`
2 parents 907b495 + 1d96723 commit 7507716

File tree

4 files changed

+32
-0
lines changed

4 files changed

+32
-0
lines changed

lib/prometheus/client/gauge.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ def set(value, labels: {})
2020
@store.set(labels: label_set_for(labels), val: value)
2121
end
2222

23+
def set_to_current_time(labels: {})
24+
@store.set(labels: label_set_for(labels), val: Time.now.to_f)
25+
end
26+
2327
# Increments Gauge value by 1 or adds the given value to the Gauge.
2428
# (The value can be negative, resulting in a decrease of the Gauge.)
2529
def increment(by: 1, labels: {})

prometheus-client.gemspec

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,5 @@ Gem::Specification.new do |s|
1717

1818
s.add_development_dependency 'benchmark-ips'
1919
s.add_development_dependency 'concurrent-ruby'
20+
s.add_development_dependency 'timecop'
2021
end

spec/prometheus/client/gauge_spec.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,30 @@
4848
end
4949
end
5050

51+
describe '#set_to_current_time' do
52+
it 'it sets the gauge to the current Unix epoch time' do
53+
Timecop.freeze(Time.at(12345.1)) do
54+
expect do
55+
gauge.set_to_current_time
56+
end.to change { gauge.get }.from(0).to(12345.1)
57+
end
58+
end
59+
60+
context "with a an expected label set" do
61+
let(:expected_labels) { [:test] }
62+
63+
it 'sets a metric value for a given label set' do
64+
Timecop.freeze(Time.at(12345.1)) do
65+
expect do
66+
expect do
67+
gauge.set_to_current_time(labels: { test: 'value' })
68+
end.to change { gauge.get(labels: { test: 'value' }) }.from(0).to(12345.1)
69+
end.to_not change { gauge.get(labels: { test: 'other' }) }
70+
end
71+
end
72+
end
73+
end
74+
5175
describe '#increment' do
5276
before do
5377
gauge.set(0, labels: RSpec.current_example.metadata[:labels] || {})

spec/spec_helper.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# encoding: UTF-8
22

33
require 'simplecov'
4+
require 'timecop'
45

56
RSpec.configure do |c|
67
c.warnings = true
@@ -9,3 +10,5 @@
910
SimpleCov.formatter = SimpleCov::Formatter::HTMLFormatter
1011

1112
SimpleCov.start
13+
14+
Timecop.safe_mode = true

0 commit comments

Comments
 (0)