diff --git a/changelog/fix_rails_time_zone_string_to_time_with_specifier.md b/changelog/fix_rails_time_zone_string_to_time_with_specifier.md new file mode 100644 index 0000000000..05d07e76fb --- /dev/null +++ b/changelog/fix_rails_time_zone_string_to_time_with_specifier.md @@ -0,0 +1 @@ +* [#1367](https://github.com/rubocop/rubocop-rails/pull/1367): Fix `Rails/TimeZone` should not report offense on `String#to_time` with timezone specifier. ([@armandmgt][]) diff --git a/lib/rubocop/cop/rails/time_zone.rb b/lib/rubocop/cop/rails/time_zone.rb index f8249609f3..a9471de299 100644 --- a/lib/rubocop/cop/rails/time_zone.rb +++ b/lib/rubocop/cop/rails/time_zone.rb @@ -28,6 +28,8 @@ module Rails # Time.zone.now # Time.zone.parse('2015-03-02T19:05:37') # Time.zone.parse('2015-03-02T19:05:37Z') # Respect ISO 8601 format with timezone specifier. + # Time.parse('2015-03-02T19:05:37Z') # Also respects ISO 8601 + # '2015-03-02T19:05:37Z'.to_time # Also respects ISO 8601 # # @example EnforcedStyle: flexible (default) # # `flexible` allows usage of `in_time_zone` instead of `zone`. @@ -67,6 +69,7 @@ def on_const(node) def on_send(node) return if !node.receiver&.str_type? || !node.method?(:to_time) + return if attach_timezone_specifier?(node.receiver) add_offense(node.loc.selector, message: MSG_STRING_TO_TIME) do |corrector| corrector.replace(node, "Time.zone.parse(#{node.receiver.source})") unless node.csend_type? diff --git a/spec/rubocop/cop/rails/time_zone_spec.rb b/spec/rubocop/cop/rails/time_zone_spec.rb index 4d8fce6250..4aacc1462d 100644 --- a/spec/rubocop/cop/rails/time_zone_spec.rb +++ b/spec/rubocop/cop/rails/time_zone_spec.rb @@ -144,6 +144,12 @@ expect_no_corrections end + it 'does not register an offense for `to_time` when attaching timezone specifier `Z`' do + expect_no_offenses(<<~RUBY) + "2012-03-02T16:05:37Z".to_time + RUBY + end + it 'does not register an offense for `to_time` without receiver' do expect_no_offenses(<<~RUBY) to_time