Skip to content

Commit 8f625ad

Browse files
authored
Merge pull request #1397 from mterada1228/fix-rails-timezone
Fix an incorrect autocorrect for `Rails/TimeZone` when Time.new has a string argument
2 parents 9748bdb + 281e686 commit 8f625ad

File tree

3 files changed

+22
-6
lines changed

3 files changed

+22
-6
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1397](https://github.com/rubocop/rubocop-rails/pull/1397): Fix an incorrect autocorrect for `Rails/TimeZone` when Time.new has a string argument. ([@mterada1228][])

lib/rubocop/cop/rails/time_zone.rb

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,9 @@ def autocorrect(corrector, node)
9797
end
9898

9999
def autocorrect_time_new(node, corrector)
100-
if node.arguments?
101-
corrector.replace(node.loc.selector, 'local')
102-
else
103-
corrector.replace(node.loc.selector, 'now')
104-
end
100+
replacement = replacement(node)
101+
102+
corrector.replace(node.loc.selector, replacement)
105103
end
106104

107105
# remove redundant `.in_time_zone` from `Time.zone.now.in_time_zone`
@@ -183,7 +181,7 @@ def method_send?(node)
183181

184182
def safe_method(method_name, node)
185183
if %w[new current].include?(method_name)
186-
node.arguments? ? 'local' : 'now'
184+
replacement(node)
187185
else
188186
method_name
189187
end
@@ -259,6 +257,12 @@ def offset_option_provided?(node)
259257
pair.key.sym_type? && pair.key.value == :in && !pair.value.nil_type?
260258
end
261259
end
260+
261+
def replacement(node)
262+
return 'now' unless node.arguments?
263+
264+
node.first_argument.str_type? ? 'parse' : 'local'
265+
end
262266
end
263267
end
264268
end

spec/rubocop/cop/rails/time_zone_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,17 @@
4646
RUBY
4747
end
4848

49+
it 'registers an offense for Time.new with string argument' do
50+
expect_offense(<<~RUBY)
51+
Time.new("2012-06-10 10:12:00")
52+
^^^ Do not use `Time.new` without zone. Use `Time.zone.parse` instead.
53+
RUBY
54+
55+
expect_correction(<<~RUBY)
56+
Time.zone.parse("2012-06-10 10:12:00")
57+
RUBY
58+
end
59+
4960
it 'does not register an offense when a .new method is called independently of the Time class' do
5061
expect_no_offenses(<<~RUBY)
5162
Range.new(1, Time.class.to_s)

0 commit comments

Comments
 (0)