From 4fd02a10c4aa735eb88a28ab3efc674b137611f5 Mon Sep 17 00:00:00 2001 From: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Fri, 15 Mar 2024 11:37:12 +0100 Subject: [PATCH] [Fix #1200] Make `Rails/TimeZone` aware of safe navigation `parse` raises on `nil` so autocorrect is not possible in this case. --- .../fix_make_rails_time_zone_aware_of_safe_navigation.md | 1 + lib/rubocop/cop/rails/time_zone.rb | 3 ++- spec/rubocop/cop/rails/time_zone_spec.rb | 9 +++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_make_rails_time_zone_aware_of_safe_navigation.md diff --git a/changelog/fix_make_rails_time_zone_aware_of_safe_navigation.md b/changelog/fix_make_rails_time_zone_aware_of_safe_navigation.md new file mode 100644 index 0000000000..8b5e502b46 --- /dev/null +++ b/changelog/fix_make_rails_time_zone_aware_of_safe_navigation.md @@ -0,0 +1 @@ +* [#1200](https://github.com/rubocop/rubocop-rails/issues/1200): Make `Rails/TimeZone` aware of safe navigation. ([@earlopain][]) diff --git a/lib/rubocop/cop/rails/time_zone.rb b/lib/rubocop/cop/rails/time_zone.rb index cb01f06dde..f8249609f3 100644 --- a/lib/rubocop/cop/rails/time_zone.rb +++ b/lib/rubocop/cop/rails/time_zone.rb @@ -69,9 +69,10 @@ 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| - corrector.replace(node, "Time.zone.parse(#{node.receiver.source})") + corrector.replace(node, "Time.zone.parse(#{node.receiver.source})") unless node.csend_type? end end + alias on_csend on_send private diff --git a/spec/rubocop/cop/rails/time_zone_spec.rb b/spec/rubocop/cop/rails/time_zone_spec.rb index 8a570b8d22..4d8fce6250 100644 --- a/spec/rubocop/cop/rails/time_zone_spec.rb +++ b/spec/rubocop/cop/rails/time_zone_spec.rb @@ -135,6 +135,15 @@ RUBY end + it 'registers an offense for `to_time` with safe navigation' do + expect_offense(<<~RUBY) + "2012-03-02 16:05:37"&.to_time + ^^^^^^^ Do not use `String#to_time` without zone. Use `Time.zone.parse` instead. + RUBY + + expect_no_corrections + end + it 'does not register an offense for `to_time` without receiver' do expect_no_offenses(<<~RUBY) to_time