Skip to content

Commit 5bc926f

Browse files
committed
Fix Rails/TimeZone should not report offense on String#to_time with timezone specifier
As `Time.parse("2012-03-02T16:05:37Z")` is allowed, `"2012-03-02T16:05:37Z".to_time` should also be allowed.
1 parent f935a0b commit 5bc926f

File tree

3 files changed

+10
-0
lines changed

3 files changed

+10
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
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][])

lib/rubocop/cop/rails/time_zone.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ module Rails
2828
# Time.zone.now
2929
# Time.zone.parse('2015-03-02T19:05:37')
3030
# Time.zone.parse('2015-03-02T19:05:37Z') # Respect ISO 8601 format with timezone specifier.
31+
# Time.parse('2015-03-02T19:05:37Z') # Also respects ISO 8601
32+
# '2015-03-02T19:05:37Z'.to_time # Also respects ISO 8601
3133
#
3234
# @example EnforcedStyle: flexible (default)
3335
# # `flexible` allows usage of `in_time_zone` instead of `zone`.
@@ -67,6 +69,7 @@ def on_const(node)
6769

6870
def on_send(node)
6971
return if !node.receiver&.str_type? || !node.method?(:to_time)
72+
return if attach_timezone_specifier?(node.receiver)
7073

7174
add_offense(node.loc.selector, message: MSG_STRING_TO_TIME) do |corrector|
7275
corrector.replace(node, "Time.zone.parse(#{node.receiver.source})") unless node.csend_type?

spec/rubocop/cop/rails/time_zone_spec.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,12 @@
144144
expect_no_corrections
145145
end
146146

147+
it 'does not register an offense for `to_time` when attaching timezone specifier `Z`' do
148+
expect_no_offenses(<<~RUBY)
149+
"2012-03-02T16:05:37Z".to_time
150+
RUBY
151+
end
152+
147153
it 'does not register an offense for `to_time` without receiver' do
148154
expect_no_offenses(<<~RUBY)
149155
to_time

0 commit comments

Comments
 (0)