Skip to content

Commit

Permalink
Merge pull request #1367 from armandmgt/feature/allow-to_time-with-sp…
Browse files Browse the repository at this point in the history
…ecifier

Fix `Rails/TimeZone` should not report offense on `String#to_time` with timezone specifier
  • Loading branch information
koic authored Oct 14, 2024
2 parents a413fe6 + 5bc926f commit ec31d1b
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1367](https://github.com/rubocop/rubocop-rails/pull/1367): Fix `Rails/TimeZone` should not report offense on `String#to_time` with timezone specifier. ([@armandmgt][])
3 changes: 3 additions & 0 deletions lib/rubocop/cop/rails/time_zone.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ module Rails
# Time.zone.now
# Time.zone.parse('2015-03-02T19:05:37')
# Time.zone.parse('2015-03-02T19:05:37Z') # Respect ISO 8601 format with timezone specifier.
# Time.parse('2015-03-02T19:05:37Z') # Also respects ISO 8601
# '2015-03-02T19:05:37Z'.to_time # Also respects ISO 8601
#
# @example EnforcedStyle: flexible (default)
# # `flexible` allows usage of `in_time_zone` instead of `zone`.
Expand Down Expand Up @@ -67,6 +69,7 @@ def on_const(node)

def on_send(node)
return if !node.receiver&.str_type? || !node.method?(:to_time)
return if attach_timezone_specifier?(node.receiver)

add_offense(node.loc.selector, message: MSG_STRING_TO_TIME) do |corrector|
corrector.replace(node, "Time.zone.parse(#{node.receiver.source})") unless node.csend_type?
Expand Down
6 changes: 6 additions & 0 deletions spec/rubocop/cop/rails/time_zone_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,12 @@
expect_no_corrections
end

it 'does not register an offense for `to_time` when attaching timezone specifier `Z`' do
expect_no_offenses(<<~RUBY)
"2012-03-02T16:05:37Z".to_time
RUBY
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 ec31d1b

Please sign in to comment.