Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix an incorrect autocorrect for Rails/TimeZone when Time.new has a string argument #1397

Merged
merged 1 commit into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading