Skip to content

Commit

Permalink
Merge pull request #253 from koic/fix_incorrect_autocorrect_for_perfo…
Browse files Browse the repository at this point in the history
…rmance_unfreeze_string

[Fix #252] Fix an incorrect auto-correct for `Performance/UnfreezeString`
  • Loading branch information
richardstewart0213 committed May 26, 2021
2 parents e681318 + a31b27c commit 6b02271
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -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

Expand Down
5 changes: 4 additions & 1 deletion lib/rubocop/cop/performance/unfreeze_string.rb
Expand Up @@ -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

Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/performance/unfreeze_string_spec.rb
Expand Up @@ -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)
+""
Expand Down

0 comments on commit 6b02271

Please sign in to comment.