diff --git a/changelog/fix_fix_stylestringconcatenation_autocorrect.md b/changelog/fix_fix_stylestringconcatenation_autocorrect.md new file mode 100644 index 00000000000..de7bec2746f --- /dev/null +++ b/changelog/fix_fix_stylestringconcatenation_autocorrect.md @@ -0,0 +1 @@ +* [#8985](https://github.com/rubocop-hq/rubocop/issues/8985): Fix `Style/StringConcatenation` autocorrect generating invalid ruby. ([@tejasbubane][]) diff --git a/lib/rubocop/cop/style/string_concatenation.rb b/lib/rubocop/cop/style/string_concatenation.rb index dae12524997..7a93e5fb53e 100644 --- a/lib/rubocop/cop/style/string_concatenation.rb +++ b/lib/rubocop/cop/style/string_concatenation.rb @@ -106,7 +106,13 @@ def replacement(parts) end end - "\"#{interpolated_parts.join}\"" + "\"#{handle_quotes(interpolated_parts).join}\"" + end + + def handle_quotes(parts) + parts.map do |part| + part == '"' ? '\"' : part + end end def single_quoted?(str_node) diff --git a/spec/rubocop/cop/style/string_concatenation_spec.rb b/spec/rubocop/cop/style/string_concatenation_spec.rb index 189348765f0..dd21173b67c 100644 --- a/spec/rubocop/cop/style/string_concatenation_spec.rb +++ b/spec/rubocop/cop/style/string_concatenation_spec.rb @@ -158,4 +158,26 @@ RUBY end end + + context 'empty quotes' do + it 'registers offense and corrects' do + expect_offense(<<-RUBY) + '"' + "foo" + '"' + ^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation. + '"' + "foo" + "'" + ^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation. + "'" + "foo" + '"' + ^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation. + "'" + "foo" + '"' + "bar" + ^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation. + RUBY + + expect_correction(<<-RUBY) + "\\\"foo\\\"" + "\\\"foo'" + "'foo\\\"" + "'foo\\\"bar" + RUBY + end + end end