From 281e6867f4074a59db39a0378bdcb32eb8620991 Mon Sep 17 00:00:00 2001 From: mterada1228 Date: Fri, 20 Dec 2024 16:36:15 +0900 Subject: [PATCH] Fix an incorrect autocorrect for `Rails/TimeZone` when Time.new has a string argument --- ...mezone_when_time_new_has_a_string_augument.md | 1 + lib/rubocop/cop/rails/time_zone.rb | 16 ++++++++++------ spec/rubocop/cop/rails/time_zone_spec.rb | 11 +++++++++++ 3 files changed, 22 insertions(+), 6 deletions(-) create mode 100644 changelog/fix_fix_an_incorrect_autocorrect_for_rails_timezone_when_time_new_has_a_string_augument.md diff --git a/changelog/fix_fix_an_incorrect_autocorrect_for_rails_timezone_when_time_new_has_a_string_augument.md b/changelog/fix_fix_an_incorrect_autocorrect_for_rails_timezone_when_time_new_has_a_string_augument.md new file mode 100644 index 0000000000..9845123015 --- /dev/null +++ b/changelog/fix_fix_an_incorrect_autocorrect_for_rails_timezone_when_time_new_has_a_string_augument.md @@ -0,0 +1 @@ +* [#1397](https://github.com/rubocop/rubocop-rails/pull/1397): Fix an incorrect autocorrect for `Rails/TimeZone` when Time.new has a string argument. ([@mterada1228][]) diff --git a/lib/rubocop/cop/rails/time_zone.rb b/lib/rubocop/cop/rails/time_zone.rb index a9471de299..80d7d97790 100644 --- a/lib/rubocop/cop/rails/time_zone.rb +++ b/lib/rubocop/cop/rails/time_zone.rb @@ -97,11 +97,9 @@ def autocorrect(corrector, node) end def autocorrect_time_new(node, corrector) - if node.arguments? - corrector.replace(node.loc.selector, 'local') - else - corrector.replace(node.loc.selector, 'now') - end + replacement = replacement(node) + + corrector.replace(node.loc.selector, replacement) end # remove redundant `.in_time_zone` from `Time.zone.now.in_time_zone` @@ -183,7 +181,7 @@ def method_send?(node) def safe_method(method_name, node) if %w[new current].include?(method_name) - node.arguments? ? 'local' : 'now' + replacement(node) else method_name end @@ -259,6 +257,12 @@ def offset_option_provided?(node) pair.key.sym_type? && pair.key.value == :in && !pair.value.nil_type? end end + + def replacement(node) + return 'now' unless node.arguments? + + node.first_argument.str_type? ? 'parse' : 'local' + end end end end diff --git a/spec/rubocop/cop/rails/time_zone_spec.rb b/spec/rubocop/cop/rails/time_zone_spec.rb index 4aacc1462d..41de6bb92b 100644 --- a/spec/rubocop/cop/rails/time_zone_spec.rb +++ b/spec/rubocop/cop/rails/time_zone_spec.rb @@ -46,6 +46,17 @@ RUBY end + it 'registers an offense for Time.new with string argument' do + expect_offense(<<~RUBY) + Time.new("2012-06-10 10:12:00") + ^^^ Do not use `Time.new` without zone. Use `Time.zone.parse` instead. + RUBY + + expect_correction(<<~RUBY) + Time.zone.parse("2012-06-10 10:12:00") + RUBY + end + it 'does not register an offense when a .new method is called independently of the Time class' do expect_no_offenses(<<~RUBY) Range.new(1, Time.class.to_s)