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