Skip to content

Commit d058c88

Browse files
authored
Merge pull request #480 from viralpraxis/fix-performance-squeeze-cop-error-on-frozen-ast-literal-node-value
Fix `Performance/Squeeze` cop error on frozen AST string node value
2 parents ad9fd62 + 9fdbe4e commit d058c88

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#480](https://github.com/rubocop/rubocop-performance/pull/480): Fix `Performance/Squeeze` cop error on frozen AST string node value. ([@viralpraxis][])

lib/rubocop/cop/performance/squeeze.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,11 @@ def on_send(node)
4646
message = format(MSG, current: bad_method, prefer: good_method)
4747

4848
add_offense(node.loc.selector, message: message) do |corrector|
49-
string_literal = to_string_literal(replace_str)
49+
# FIXME: When requiring only RuboCop 1.70.0 and above,
50+
# `dup` in `replace_str.dup` becomes unnecessary, as
51+
# frozen strings are handled in the `to_string_literal`
52+
# implementation. Please remove it.
53+
string_literal = to_string_literal(replace_str.dup)
5054
new_code = "#{receiver.source}#{node.loc.dot.source}#{good_method}(#{string_literal})"
5155

5256
corrector.replace(node, new_code)

spec/rubocop/cop/performance/squeeze_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,15 @@
5151
str.gsub(/a+/, 'b')
5252
RUBY
5353
end
54+
55+
it 'registers an offense when AST string literal might be frozen' do
56+
expect_offense(<<~'RUBY')
57+
str.gsub(/\n+/, ?\n)
58+
^^^^ Use `squeeze` instead of `gsub`.
59+
RUBY
60+
61+
expect_correction(<<~'RUBY')
62+
str.squeeze("\n")
63+
RUBY
64+
end
5465
end

0 commit comments

Comments
 (0)