Skip to content

Commit

Permalink
Merge pull request #676 from airbrake/time-truncate-simplification
Browse files Browse the repository at this point in the history
time_truncate: simplify conversion code and tests
  • Loading branch information
kyrylo authored Jan 10, 2022
2 parents f9b152e + e1d54bb commit ac85156
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 15 deletions.
5 changes: 2 additions & 3 deletions lib/airbrake-ruby/time_truncate.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ module Airbrake
module TimeTruncate
# Truncate +time+ to floor minute and turn it into an RFC3339 timestamp.
#
# @param [Time] time
# @param [Time, Integer, Float] time
# @return [String]
def self.utc_truncate_minutes(time)
# time does not have getutc method instead of Time on Rails 7.0.0
tm = time.respond_to?(:getutc) ? time.getutc : Time.at(time).getutc
tm = Time.at(time).getutc

Time.utc(tm.year, tm.month, tm.day, tm.hour, tm.min).to_datetime.rfc3339
end
Expand Down
33 changes: 21 additions & 12 deletions spec/time_truncate_spec.rb
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
RSpec.describe Airbrake::TimeTruncate do
time = Time.new(2018, 1, 1, 0, 0, 20, 0)
time_with_zone = Time.new(2018, 1, 1, 0, 0, 20, '-05:00')

describe "#utc_truncate_minutes" do
it "truncates time to the floor minute and returns an RFC3339 timestamp" do
time = Time.new(2018, 1, 1, 0, 0, 20, 0)
expect(described_class.utc_truncate_minutes(time))
.to eq('2018-01-01T00:00:00+00:00')
shared_examples 'time conversion' do |t|
it "truncates the time to the floor minute and returns an RFC3339 timestamp" do
expect(described_class.utc_truncate_minutes(t))
.to eq('2018-01-01T00:00:00+00:00')
end

it "converts time with zone to UTC" do
expect(described_class.utc_truncate_minutes(time_with_zone))
.to eq('2018-01-01T05:00:00+00:00')
end
end

context "when the time argument is a Time object" do
include_examples 'time conversion', time
end

it "converts time with zone to UTC" do
time = Time.new(2018, 1, 1, 0, 0, 20, '-05:00')
expect(described_class.utc_truncate_minutes(time))
.to eq('2018-01-01T05:00:00+00:00')
context "when the time argument is a Float" do
include_examples 'time conversion', time.to_f
end

it "converts it well even if the argument is an instance of Float" do
time = Time.new(2018, 1, 1, 0, 0, 20, '-05:00').to_f
expect(described_class.utc_truncate_minutes(time))
.to eq('2018-01-01T05:00:00+00:00')
context "when the time argument is an Integer" do
include_examples 'time conversion', time.to_i
end
end
end

0 comments on commit ac85156

Please sign in to comment.