From ce6056df658bbeb1fe7368da232f54ec292fe076 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Tue, 12 Sep 2023 01:19:53 +0900 Subject: [PATCH] [Fix #1108] Fix an incorrect autocorrect for `Rails/TimeZone` Fixes #1108. This PR fixes an incorrect autocorrect for `Rails/TimeZone` when using `String#to_time`. --- changelog/fix_an_incorrect_autocorrect_for_rails_time_zone.md | 1 + lib/rubocop/cop/rails/time_zone.rb | 2 +- spec/rubocop/cop/rails/time_zone_spec.rb | 4 ++++ 3 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_an_incorrect_autocorrect_for_rails_time_zone.md diff --git a/changelog/fix_an_incorrect_autocorrect_for_rails_time_zone.md b/changelog/fix_an_incorrect_autocorrect_for_rails_time_zone.md new file mode 100644 index 0000000000..2ac79e569d --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_rails_time_zone.md @@ -0,0 +1 @@ +* [#1108](https://github.com/rubocop/rubocop-rails/issues/1108): Fix an incorrect autocorrect for `Rails/TimeZone` when using `String#to_time`. ([@koic][]) diff --git a/lib/rubocop/cop/rails/time_zone.rb b/lib/rubocop/cop/rails/time_zone.rb index 1ad9768e3d..cb01f06dde 100644 --- a/lib/rubocop/cop/rails/time_zone.rb +++ b/lib/rubocop/cop/rails/time_zone.rb @@ -69,7 +69,7 @@ def on_send(node) return if !node.receiver&.str_type? || !node.method?(:to_time) add_offense(node.loc.selector, message: MSG_STRING_TO_TIME) do |corrector| - autocorrect(corrector, node) + corrector.replace(node, "Time.zone.parse(#{node.receiver.source})") end end diff --git a/spec/rubocop/cop/rails/time_zone_spec.rb b/spec/rubocop/cop/rails/time_zone_spec.rb index be0ca5bd5e..8a570b8d22 100644 --- a/spec/rubocop/cop/rails/time_zone_spec.rb +++ b/spec/rubocop/cop/rails/time_zone_spec.rb @@ -129,6 +129,10 @@ "2012-03-02 16:05:37".to_time ^^^^^^^ Do not use `String#to_time` without zone. Use `Time.zone.parse` instead. RUBY + + expect_correction(<<~RUBY) + Time.zone.parse("2012-03-02 16:05:37") + RUBY end it 'does not register an offense for `to_time` without receiver' do