Skip to content

Commit

Permalink
Tweaks to json generation
Browse files Browse the repository at this point in the history
  • Loading branch information
jnunemaker committed Oct 29, 2023
1 parent 79da99f commit 6034d65
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 9 deletions.
12 changes: 3 additions & 9 deletions lib/flipper/cloud/telemetry.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,15 +112,9 @@ def post_to_cloud(drained)
return if drained.empty?
logger.debug "pid=#{@pid} name=flipper_telemetry action=post_to_cloud"

enabled_metrics = drained.inject([]) do |array, (metric, value)|
array << {
key: metric.key,
time: metric.time,
result: metric.result,
value: value,
}
array
end
enabled_metrics = drained.map { |metric, value|
metric.as_json(with: {"value" => value})
}

body = JSON.generate({
request_id: SecureRandom.uuid,
Expand Down
14 changes: 14 additions & 0 deletions lib/flipper/cloud/telemetry/metric.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,20 @@ def initialize(key, result, time = Time.now)
@time = time.to_i / 60 * 60
end

def as_json(options = {})
data = {
"key" => key.to_s,
"time" => time,
"result" => result,
}

if options[:with]
data.merge!(options[:with])
end

data
end

def eql?(other)
self.class.eql?(other.class) &&
@key == other.key && @time == other.time && @result == other.result
Expand Down
21 changes: 21 additions & 0 deletions spec/flipper/cloud/telemetry/metric_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,25 @@
expect(metric.hash).to eq([described_class, metric.key, metric.time, metric.result].hash)
end
end

describe "#as_json" do
it "returns key time and result" do
metric = described_class.new(:search, true, 1696793160)
expect(metric.as_json).to eq({
"key" => "search",
"result" => true,
"time" => 1696793160,
})
end

it "can include other hashes" do
metric = described_class.new(:search, true, 1696793160)
expect(metric.as_json(with: {"value" => 2})).to eq({
"key" => "search",
"result" => true,
"time" => 1696793160,
"value" => 2,
})
end
end
end

0 comments on commit 6034d65

Please sign in to comment.