From 95599b2b9a4b424667c6272c2e73bf96c9311c72 Mon Sep 17 00:00:00 2001 From: Geremia Taglialatela Date: Sun, 17 Sep 2023 22:46:50 +0200 Subject: [PATCH] Cosmetic rewrite of string_to_utc_time method - 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` --- .rubocop_todo.yml | 13 ------------- lib/chrono_model/conversions.rb | 18 ++++++++---------- 2 files changed, 8 insertions(+), 23 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index f80b067..2f38e0c 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -98,20 +98,12 @@ Style/ExplicitBlockArgument: - 'lib/chrono_model/adapter/migrations.rb' - 'lib/chrono_model/time_machine/history_model.rb' -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: format, sprintf, percent -Style/FormatString: - Exclude: - - 'lib/chrono_model/conversions.rb' - # This cop supports safe autocorrection (--autocorrect). # Configuration parameters: MinBodyLength, AllowConsecutiveConditionals. Style/GuardClause: Exclude: - 'lib/active_record/connection_adapters/chronomodel_adapter.rb' - 'lib/chrono_model/adapter/migrations.rb' - - 'lib/chrono_model/conversions.rb' - 'lib/chrono_model/time_machine.rb' # This cop supports unsafe autocorrection (--autocorrect-all). @@ -162,11 +154,6 @@ Style/PercentLiteralDelimiters: - 'lib/chrono_model/time_machine/time_query.rb' - 'lib/chrono_model/time_machine/timeline.rb' -# This cop supports safe autocorrection (--autocorrect). -Style/PerlBackrefs: - Exclude: - - 'lib/chrono_model/conversions.rb' - # This cop supports safe autocorrection (--autocorrect). Style/RedundantSelf: Exclude: diff --git a/lib/chrono_model/conversions.rb b/lib/chrono_model/conversions.rb index 0f223fa..f43d02b 100644 --- a/lib/chrono_model/conversions.rb +++ b/lib/chrono_model/conversions.rb @@ -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)