Skip to content

Commit

Permalink
Merge pull request rubocop#10277 from koic/fix_incorrect_autocorrect_…
Browse files Browse the repository at this point in the history
…for_style_redundant_interpolation

[Fix rubocop#10276] Fix an incorrect autocorrect for `Style/RedundantInterpolation`
  • Loading branch information
koic authored Dec 1, 2021
2 parents 958e544 + 45ea08b commit 84ac070
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#10276](https://github.com/rubocop/rubocop/issues/10276): Fix an incorrect autocorrect for `Style/RedundantInterpolation` when using a method call without parentheses in string interpolation. ([@koic][])
20 changes: 17 additions & 3 deletions lib/rubocop/cop/style/redundant_interpolation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,20 @@ def autocorrect_variable_interpolation(corrector, embedded_node, node)
end

def autocorrect_single_variable_interpolation(corrector, embedded_node, node)
variable_loc = embedded_node.children.first.loc
replacement = "#{variable_loc.expression.source}.to_s"
embedded_var = embedded_node.children.first

corrector.replace(node, replacement)
source = if require_parentheses?(embedded_var)
receiver = range_between(
embedded_var.loc.expression.begin_pos, embedded_var.loc.selector.end_pos
)
arguments = embedded_var.arguments.map(&:source).join(', ')

"#{receiver.source}(#{arguments})"
else
embedded_var.source
end

corrector.replace(node, "#{source}.to_s")
end

def autocorrect_other(corrector, embedded_node, node)
Expand All @@ -97,6 +107,10 @@ def autocorrect_other(corrector, embedded_node, node)
corrector.replace(embedded_loc.begin, '(')
corrector.replace(embedded_loc.end, ').to_s')
end

def require_parentheses?(node)
node.send_type? && !node.arguments.count.zero? && !node.parenthesized_call?
end
end
end
end
Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/style/redundant_interpolation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,28 @@
RUBY
end

it 'registers an offense for "#{do_something 42}"' do
expect_offense(<<~'RUBY')
"#{do_something 42}"
^^^^^^^^^^^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY

expect_correction(<<~'RUBY')
do_something(42).to_s
RUBY
end

it 'registers an offense for "#{foo.do_something 42}"' do
expect_offense(<<~'RUBY')
"#{foo.do_something 42}"
^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY

expect_correction(<<~'RUBY')
foo.do_something(42).to_s
RUBY
end

it 'registers an offense for "#{var}"' do
expect_offense(<<~'RUBY')
var = 1; "#{var}"
Expand Down

0 comments on commit 84ac070

Please sign in to comment.