Skip to content

Commit

Permalink
Fix an error for Style/StringConcatenation when correcting nested c…
Browse files Browse the repository at this point in the history
…oncatenable parts
  • Loading branch information
fatkodima authored and bbatsov committed Oct 15, 2020
1 parent de5b74f commit 171eaf3
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#8892](https://github.com/rubocop-hq/rubocop/issues/8892): Fix an error for `Style/StringConcatenation` when correcting nested concatenable parts. ([@fatkodima][])

## 0.93.1 (2020-10-12)

### Bug fixes
Expand Down
14 changes: 13 additions & 1 deletion lib/rubocop/cop/style/string_concatenation.rb
Expand Up @@ -33,6 +33,10 @@ class StringConcatenation < Base
}
PATTERN

def on_new_investigation
@corrected_nodes = nil
end

def on_send(node)
return unless string_concatenation?(node)

Expand All @@ -42,8 +46,12 @@ def on_send(node)
collect_parts(topmost_plus_node, parts)

add_offense(topmost_plus_node) do |corrector|
if parts.none? { |part| uncorrectable?(part) }
correctable_parts = parts.none? { |part| uncorrectable?(part) }
if correctable_parts && !corrected_ancestor?(topmost_plus_node)
corrector.replace(topmost_plus_node, replacement(parts))

@corrected_nodes ||= Set.new.compare_by_identity
@corrected_nodes.add(topmost_plus_node)
end
end
end
Expand Down Expand Up @@ -80,6 +88,10 @@ def uncorrectable?(part)
part.each_descendant(:block).any?
end

def corrected_ancestor?(node)
node.each_ancestor(:send).any? { |ancestor| @corrected_nodes&.include?(ancestor) }
end

def replacement(parts)
interpolated_parts =
parts.map do |part|
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/style/string_concatenation_spec.rb
Expand Up @@ -36,6 +36,18 @@
RUBY
end

it 'correctly handles nested concatenable parts' do
expect_offense(<<~RUBY)
(user.vip? ? greeting + ', ' : '') + user.name + ' <' + user.email + '>'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY

expect_correction(<<~RUBY)
"\#{(user.vip? ? "\#{greeting}, " : '')}\#{user.name} <\#{user.email}>"
RUBY
end

it 'does not register an offense when using `+` with all non string arguments' do
expect_no_offenses(<<~RUBY)
user.name + user.email
Expand Down

0 comments on commit 171eaf3

Please sign in to comment.