Skip to content

Commit

Permalink
Merge pull request #1251 from Earlopain/make-time-zone-aware-of-safe-…
Browse files Browse the repository at this point in the history
…navigation

[Fix #1200] Make `Rails/TimeZone` aware of safe navigation
  • Loading branch information
koic authored Mar 21, 2024
2 parents 2f893da + 4fd02a1 commit 650e783
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 650e783

Please sign in to comment.