Skip to content

Commit

Permalink
[Fix rubocop#10685] Fix a false positive for Style/StringConcatenation
Browse files Browse the repository at this point in the history
Fixes rubocop#10685.

This PR fixes a false positive for `Style/StringConcatenation`
when `Mode: conservative` and first operand is not string literal.

This also resolves the following feedback:
rubocop#9153 (comment)

`Mode: conservative` should be allowed considering the possibility that
receiver is a `Pathname` object.
  • Loading branch information
koic committed Jun 2, 2022
1 parent 5bec7c7 commit 0a91fb2
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 9 deletions.
@@ -0,0 +1 @@
* [#10685](https://github.com/rubocop/rubocop/issues/10685): Fix a false positive for `Style/StringConcatenation` when `Mode: conservative` and first operand is not string literal. ([@koic][])
11 changes: 5 additions & 6 deletions lib/rubocop/cop/style/string_concatenation.rb
Expand Up @@ -76,7 +76,7 @@ def on_send(node)

topmost_plus_node = find_topmost_plus_node(node)
parts = collect_parts(topmost_plus_node)
return unless parts[0..-2].any? { |receiver_node| offensive_for_mode?(receiver_node) }
return if mode == :conservative && !parts.first.str_type?

register_offense(topmost_plus_node, parts)
end
Expand All @@ -95,11 +95,6 @@ def register_offense(topmost_plus_node, parts)
end
end

def offensive_for_mode?(receiver_node)
mode = cop_config['Mode'].to_sym
mode == :aggressive || (mode == :conservative && receiver_node.str_type?)
end

def line_end_concatenation?(node)
# If the concatenation happens at the end of the line,
# and both the receiver and argument are strings, allow
Expand Down Expand Up @@ -173,6 +168,10 @@ def handle_quotes(parts)
def single_quoted?(str_node)
str_node.source.start_with?("'")
end

def mode
cop_config['Mode'].to_sym
end
end
end
end
Expand Down
4 changes: 1 addition & 3 deletions spec/rubocop/cop/style/string_concatenation_spec.rb
Expand Up @@ -224,6 +224,7 @@
expect_no_offenses(<<~RUBY)
user.name + "!!"
user.name + "<"
user.name + "<" + "user.email" + ">"
RUBY
end
end
Expand All @@ -235,14 +236,11 @@
^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
"Hello " + user.name + "!!"
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
user.name + "<" + "user.email" + ">"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY

expect_correction(<<~RUBY)
"Hello \#{user.name}"
"Hello \#{user.name}!!"
"\#{user.name}<user.email>"
RUBY
end
end
Expand Down

0 comments on commit 0a91fb2

Please sign in to comment.