Skip to content

Commit

Permalink
[Fix rubocop#384] Support optimized String#dup for `Performance/Unf…
Browse files Browse the repository at this point in the history
…reezeString`

Resolves rubocop#384.

This PR supports optimized `String#dup` for `Performance/UnfreezeString` when Ruby 3.3+.
  • Loading branch information
koic committed Dec 6, 2023
1 parent 461168f commit 0c426d6
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#384](https://github.com/rubocop/rubocop-performance/issues/384): Support optimized `String#dup` for `Performance/UnfreezeString` when Ruby 3.3+. ([@koic][])
6 changes: 3 additions & 3 deletions lib/rubocop/cop/performance/unfreeze_string.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ module Performance
#
# @example
# # bad
# ''.dup
# "something".dup
# ''.dup # when Ruby 3.2 or lower
# "something".dup # when Ruby 3.2 or lower
# String.new
# String.new('')
# String.new('something')
Expand Down Expand Up @@ -45,7 +45,7 @@ class UnfreezeString < Base
PATTERN

def on_send(node)
return unless dup_string?(node) || string_new?(node)
return unless (dup_string?(node) && target_ruby_version <= 3.2) || string_new?(node)

add_offense(node) do |corrector|
string_value = "+#{string_value(node)}"
Expand Down
26 changes: 18 additions & 8 deletions spec/rubocop/cop/performance/unfreeze_string_spec.rb
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
# frozen_string_literal: true

RSpec.describe RuboCop::Cop::Performance::UnfreezeString, :config do
it 'registers an offense and corrects for an empty string with `.dup`' do
expect_offense(<<~RUBY)
"".dup
^^^^^^ Use unary plus to get an unfrozen string literal.
RUBY
context 'when Ruby <= 3.2', :ruby32 do
it 'registers an offense and corrects for an empty string with `.dup`' do
expect_offense(<<~RUBY)
"".dup
^^^^^^ Use unary plus to get an unfrozen string literal.
RUBY

expect_correction(<<~RUBY)
+""
RUBY
expect_correction(<<~RUBY)
+""
RUBY
end
end

context 'when Ruby >= 3.3', :ruby33 do
it 'does not register an offense and corrects for an empty string with `.dup`' do
expect_no_offenses(<<~RUBY)
"".dup
RUBY
end
end

it 'registers an offense and corrects for a string with `.dup`' do
Expand Down

0 comments on commit 0c426d6

Please sign in to comment.