diff --git a/CHANGELOG.md b/CHANGELOG.md index 90ff270650c..74a7c5edeb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ * [#8514](https://github.com/rubocop-hq/rubocop/issues/8514): Correct multiple `Style/MethodDefParentheses` per file. ([@rdunlop][]) * [#8825](https://github.com/rubocop-hq/rubocop/issues/8825): Fix crash in `Style/ExplicitBlockArgument` when code is called outside of a method. ([@ghiculescu][]) * [#8354](https://github.com/rubocop-hq/rubocop/issues/8354): Detect regexp named captures in `Style/CaseLikeIf` cop. ([@dsavochkin][]) +* [#8830](https://github.com/rubocop-hq/rubocop/issues/8830): Fix bad autocorrect of `Style/StringConcatenation` when string includes double quotes. ([@tleish][]) ### Changes diff --git a/lib/rubocop/cop/style/string_concatenation.rb b/lib/rubocop/cop/style/string_concatenation.rb index 8936f5bad0f..8f33df333d9 100644 --- a/lib/rubocop/cop/style/string_concatenation.rb +++ b/lib/rubocop/cop/style/string_concatenation.rb @@ -87,7 +87,7 @@ def replacement(parts) if single_quoted?(part) part.value.gsub('\\') { '\\\\' } else - escape_string(part.value) + part.value.inspect[1..-2] end else "\#{#{part.source}}" diff --git a/spec/rubocop/cop/style/string_concatenation_spec.rb b/spec/rubocop/cop/style/string_concatenation_spec.rb index d0b12cf46b7..85207e6dcd2 100644 --- a/spec/rubocop/cop/style/string_concatenation_spec.rb +++ b/spec/rubocop/cop/style/string_concatenation_spec.rb @@ -122,4 +122,28 @@ expect_no_corrections end end + + context 'double quotes inside string' do + it 'registers an offense and corrects with double quotes' do + expect_offense(<<-RUBY) + email_with_name = "He said " + "\\\"Arrest that man!\\\"." + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation. + RUBY + + expect_correction(<<-RUBY) + email_with_name = "He said \\\"Arrest that man!\\\"." + RUBY + end + + it 'registers an offense and corrects with percentage quotes' do + expect_offense(<<-RUBY) + email_with_name = %(He said ) + %("Arrest that man!".) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation. + RUBY + + expect_correction(<<-RUBY) + email_with_name = "He said \\\"Arrest that man!\\\"." + RUBY + end + end end