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 error for Style/StringConcatenation when correcting nested concatenable parts #8893

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