Skip to content

Commit

Permalink
Fix an incorrect autocorrect for Rails/TimeZone when Time.new has a…
Browse files Browse the repository at this point in the history
… string argument
  • Loading branch information
mterada1228 committed Dec 28, 2024
1 parent c6f869b commit 281e686
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +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][])
16 changes: 10 additions & 6 deletions lib/rubocop/cop/rails/time_zone.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,9 @@ def autocorrect(corrector, node)
end

def autocorrect_time_new(node, corrector)
if node.arguments?
corrector.replace(node.loc.selector, 'local')
else
corrector.replace(node.loc.selector, 'now')
end
replacement = replacement(node)

corrector.replace(node.loc.selector, replacement)
end

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

def safe_method(method_name, node)
if %w[new current].include?(method_name)
node.arguments? ? 'local' : 'now'
replacement(node)
else
method_name
end
Expand Down Expand Up @@ -259,6 +257,12 @@ def offset_option_provided?(node)
pair.key.sym_type? && pair.key.value == :in && !pair.value.nil_type?
end
end

def replacement(node)
return 'now' unless node.arguments?

node.first_argument.str_type? ? 'parse' : 'local'
end
end
end
end
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/time_zone_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@
RUBY
end

it 'registers an offense for Time.new with string argument' do
expect_offense(<<~RUBY)
Time.new("2012-06-10 10:12:00")
^^^ Do not use `Time.new` without zone. Use `Time.zone.parse` instead.
RUBY

expect_correction(<<~RUBY)
Time.zone.parse("2012-06-10 10:12:00")
RUBY
end

it 'does not register an offense when a .new method is called independently of the Time class' do
expect_no_offenses(<<~RUBY)
Range.new(1, Time.class.to_s)
Expand Down

0 comments on commit 281e686

Please sign in to comment.