Skip to content

Commit

Permalink
Cosmetic rewrite of string_to_utc_time method
Browse files Browse the repository at this point in the history
- Add guard clauses
- Use format instead of sprintf (same performance)
- Disable `Style/PerlBackrefs` cop: it is the most performant way of
  implementing this method

NOTE: this implementation is 5x faster than `Time.parse`
  • Loading branch information
tagliala committed Sep 17, 2023
1 parent e479f80 commit 95599b2
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 23 deletions.
13 changes: 0 additions & 13 deletions .rubocop_todo.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 8 additions & 10 deletions lib/chrono_model/conversions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,18 @@ module Conversions

ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(?:\.(\d+))?\z/.freeze

# rubocop:disable Style/PerlBackrefs
def string_to_utc_time(string)
return string if string.is_a?(Time)

if string =~ ISO_DATETIME
# .1 is .100000, not .000001
usec =
if $7.nil?
'000000'
else
$7.ljust(6, '0')
end
Time.utc $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, usec.to_i
end
return unless string =~ ISO_DATETIME

# .1 is .100000, not .000001
usec = $7.ljust(6, '0') unless $7.nil?

Time.utc $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, usec.to_i
end
# rubocop:enable Style/PerlBackrefs

def time_to_utc_string(time)
time.to_formatted_s(:db) << '.' << format('%06d', time.usec)
Expand Down

0 comments on commit 95599b2

Please sign in to comment.