Skip to content

Commit

Permalink
Merge pull request #9633 from koic/fix_incorrect_autocorrect_for_lint…
Browse files Browse the repository at this point in the history
…_number_conversion

Fix an incorrect auto-correct for `Lint/NumberConversion`
  • Loading branch information
koic committed Mar 24, 2021
2 parents 98ff684 + ee40857 commit 107624a
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
@@ -0,0 +1 @@
* [#9633](https://github.com/rubocop/rubocop/pull/9633): Fix an incorrect auto-correct for `Lint/NumberConversion` when `to_i` method in symbol form. ([@koic][])
7 changes: 7 additions & 0 deletions lib/rubocop/cop/lint/number_conversion.rb
Expand Up @@ -105,6 +105,8 @@ def handle_as_symbol(node)
corrected_method: correct_sym_method(to_method)
)
add_offense(node, message: message) do |corrector|
remove_parentheses(corrector, node) if node.parenthesized?

corrector.replace(sym_node, correct_sym_method(to_method))
end
end
Expand All @@ -120,6 +122,11 @@ def correct_sym_method(to_method)
"{ |i| #{body} }"
end

def remove_parentheses(corrector, node)
corrector.replace(node.loc.begin, ' ')
corrector.remove(node.loc.end)
end

def ignore_receiver?(receiver)
if receiver.send_type? && ignored_method?(receiver.method_name)
true
Expand Down
17 changes: 14 additions & 3 deletions spec/rubocop/cop/lint/number_conversion_spec.rb
Expand Up @@ -131,7 +131,18 @@
RUBY

expect_correction(<<~RUBY)
"1,2,3,foo,5,6,7,8".split(',').map({ |i| Integer(i, 10) })
"1,2,3,foo,5,6,7,8".split(',').map { |i| Integer(i, 10) }
RUBY
end

it 'registers offense and autocorrects without parentheses' do
expect_offense(<<~RUBY)
"1,2,3,foo,5,6,7,8".split(',').map &:to_i
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using &:to_i, use stricter { |i| Integer(i, 10) }.
RUBY

expect_correction(<<~RUBY)
"1,2,3,foo,5,6,7,8".split(',').map { |i| Integer(i, 10) }
RUBY
end

Expand All @@ -142,7 +153,7 @@
RUBY

expect_correction(<<~RUBY)
"foo".try({ |i| Float(i) })
"foo".try { |i| Float(i) }
RUBY
end

Expand All @@ -153,7 +164,7 @@
RUBY

expect_correction(<<~RUBY)
"foo".send({ |i| Complex(i) })
"foo".send { |i| Complex(i) }
RUBY
end
end
Expand Down

0 comments on commit 107624a

Please sign in to comment.