From 56e74c1ef2baed86606684b4982b6efd5a4c4990 Mon Sep 17 00:00:00 2001 From: MarttiCheng Date: Tue, 25 May 2021 11:05:05 +0900 Subject: [PATCH] [Fix #252] Fix an incorrect auto-correct for `Performance/UnfreezeString` Fixes #252. This PR fixes an incorrect auto-correct for `Performance/UnfreezeString` when invoking a method after `String.new` with a string. --- CHANGELOG.md | 1 + lib/rubocop/cop/performance/unfreeze_string.rb | 5 ++++- spec/rubocop/cop/performance/unfreeze_string_spec.rb | 11 +++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3219e38..4de91c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ * [#247](https://github.com/rubocop/rubocop-performance/issues/247): Fix an incorrect auto-correct for `Performance/MapCompact` when using multi-line trailing dot method calls. ([@koic][]) * [#249](https://github.com/rubocop/rubocop-performance/issues/249): Fix a false positive for `Performance/RedundantStringChars` when using `str.chars.last` and `str.chars.drop`. ([@koic][]) +* [#252](https://github.com/rubocop/rubocop-performance/issues/252): Fix an incorrect auto-correct for `Performance/UnfreezeString` when invoking a method after `String.new` with a string. ([@koic][]) ### Changes diff --git a/lib/rubocop/cop/performance/unfreeze_string.rb b/lib/rubocop/cop/performance/unfreeze_string.rb index 2a820be..76119f2 100644 --- a/lib/rubocop/cop/performance/unfreeze_string.rb +++ b/lib/rubocop/cop/performance/unfreeze_string.rb @@ -45,7 +45,10 @@ def on_send(node) return unless dup_string?(node) || string_new?(node) add_offense(node) do |corrector| - corrector.replace(node, "+#{string_value(node)}") + string_value = "+#{string_value(node)}" + string_value = "(#{string_value})" if node.parent&.send_type? + + corrector.replace(node, string_value) end end diff --git a/spec/rubocop/cop/performance/unfreeze_string_spec.rb b/spec/rubocop/cop/performance/unfreeze_string_spec.rb index 5fe1421..0aec4c4 100644 --- a/spec/rubocop/cop/performance/unfreeze_string_spec.rb +++ b/spec/rubocop/cop/performance/unfreeze_string_spec.rb @@ -85,6 +85,17 @@ RUBY end + it 'registers an offense and corrects when invoking a method after `String.new` with a string' do + expect_offense(<<~RUBY) + String.new('foo').force_encoding(Encoding::ASCII) + ^^^^^^^^^^^^^^^^^ Use unary plus to get an unfrozen string literal. + RUBY + + expect_correction(<<~RUBY) + (+'foo').force_encoding(Encoding::ASCII) + RUBY + end + it 'accepts an empty string with unary plus operator' do expect_no_offenses(<<~RUBY) +""