Skip to content

Commit 8e43737

Browse files
authored
Merge pull request #1096 from koic/make_rails_time_zone_aware_of_string_to_time
[Fix #1094] Make `Rails/TimeZone` aware of `String#to_time`
2 parents 930b96a + 49560be commit 8e43737

File tree

3 files changed

+26
-5
lines changed

3 files changed

+26
-5
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1094](https://github.com/rubocop/rubocop-rails/issues/1094): Make `Rails/TimeZone` aware of `String#to_time`. ([@koic][])

lib/rubocop/cop/rails/time_zone.rb

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ module Rails
2121
# # bad
2222
# Time.now
2323
# Time.parse('2015-03-02T19:05:37')
24+
# '2015-03-02T19:05:37'.to_time
2425
#
2526
# # good
2627
# Time.current
@@ -44,19 +45,17 @@ class TimeZone < Base
4445
extend AutoCorrector
4546

4647
MSG = 'Do not use `%<current>s` without zone. Use `%<prefer>s` instead.'
47-
4848
MSG_ACCEPTABLE = 'Do not use `%<current>s` without zone. Use one of %<prefer>s instead.'
49-
5049
MSG_LOCALTIME = 'Do not use `Time.localtime` without offset or zone.'
50+
MSG_STRING_TO_TIME = 'Do not use `String#to_time` without zone. Use `Time.zone.parse` instead.'
5151

5252
GOOD_METHODS = %i[zone zone_default find_zone find_zone!].freeze
53-
5453
DANGEROUS_METHODS = %i[now local new parse at].freeze
55-
5654
ACCEPTED_METHODS = %i[in_time_zone utc getlocal xmlschema iso8601 jisx0301 rfc3339 httpdate to_i to_f].freeze
57-
5855
TIMEZONE_SPECIFIER = /([A-Za-z]|[+-]\d{2}:?\d{2})\z/.freeze
5956

57+
RESTRICT_ON_SEND = %i[to_time].freeze
58+
6059
def on_const(node)
6160
mod, klass = *node
6261
# we should only check core classes
@@ -66,6 +65,14 @@ def on_const(node)
6665
check_time_node(klass, node.parent) if klass == :Time
6766
end
6867

68+
def on_send(node)
69+
return if !node.receiver&.str_type? || !node.method?(:to_time)
70+
71+
add_offense(node.loc.selector, message: MSG_STRING_TO_TIME) do |corrector|
72+
autocorrect(corrector, node)
73+
end
74+
end
75+
6976
private
7077

7178
def autocorrect(corrector, node)

spec/rubocop/cop/rails/time_zone_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,19 @@
124124
end
125125
end
126126

127+
it 'registers an offense for `String#to_time`' do
128+
expect_offense(<<~RUBY)
129+
"2012-03-02 16:05:37".to_time
130+
^^^^^^^ Do not use `String#to_time` without zone. Use `Time.zone.parse` instead.
131+
RUBY
132+
end
133+
134+
it 'does not register an offense for `to_time` without receiver' do
135+
expect_no_offenses(<<~RUBY)
136+
to_time
137+
RUBY
138+
end
139+
127140
it 'registers an offense for Time.parse' do
128141
expect_offense(<<~RUBY)
129142
Time.parse("2012-03-02 16:05:37")

0 commit comments

Comments
 (0)