Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Performance/Squeeze cop error on frozen AST string node value #480

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#480](https://github.com/rubocop/rubocop-performance/pull/480): Fix `Performance/Squeeze` cop error on frozen AST string node value. ([@viralpraxis][])
6 changes: 5 additions & 1 deletion lib/rubocop/cop/performance/squeeze.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@ def on_send(node)
message = format(MSG, current: bad_method, prefer: good_method)

add_offense(node.loc.selector, message: message) do |corrector|
string_literal = to_string_literal(replace_str)
# FIXME: When requiring only RuboCop 1.70.0 and above,
# `dup` in `replace_str.dup` becomes unnecessary, as
# frozen strings are handled in the `to_string_literal`
# implementation. Please remove it.
string_literal = to_string_literal(replace_str.dup)
Copy link
Member

@koic koic Dec 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a FIXME comment? e.g.:

Suggested change
string_literal = to_string_literal(replace_str.dup)
# FIXME: When requiring only RuboCop 1.70.0 and above,
# `dup` in `replace_str.dup` becomes unnecessary, so please remove it.
string_literal = to_string_literal(replace_str.dup)

new_code = "#{receiver.source}#{node.loc.dot.source}#{good_method}(#{string_literal})"

corrector.replace(node, new_code)
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/performance/squeeze_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,15 @@
str.gsub(/a+/, 'b')
RUBY
end

it 'registers an offense when AST string literal might be frozen' do
expect_offense(<<~'RUBY')
str.gsub(/\n+/, ?\n)
^^^^ Use `squeeze` instead of `gsub`.
RUBY

expect_correction(<<~'RUBY')
str.squeeze("\n")
RUBY
end
end
Loading