Skip to content

Commit

Permalink
[Fix rubocop#1200] Make Rails/TimeZone aware of safe navigation
Browse files Browse the repository at this point in the history
`parse` raises on `nil` so autocorrect is not possible in this case.
  • Loading branch information
Earlopain committed Mar 15, 2024
1 parent 83c0968 commit 165d849
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1200](https://github.com/rubocop/rubocop-rails/issues/1200): Make `Rails/TimeZone` aware of safe navigation. ([@earlopain][])
3 changes: 2 additions & 1 deletion lib/rubocop/cop/rails/time_zone.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
9 changes: 9 additions & 0 deletions spec/rubocop/cop/rails/time_zone_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 165d849

Please sign in to comment.