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 #10216] Fix an incorrect autocorrect for Style/SelectByRegexp #10218

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1 @@
* [#10216](https://github.com/rubocop/rubocop/issues/10216): Fix an incorrect autocorrect for `Style/SelectByRegexp` when using `lvar =~ blockvar` in a block. ([@koic][])
7 changes: 4 additions & 3 deletions lib/rubocop/cop/style/select_by_regexp.rb
Expand Up @@ -85,7 +85,7 @@ def on_send(node)
return unless (regexp_method_send_node = extract_send_node(block_node))
return if match_predicate_without_receiver?(regexp_method_send_node)

regexp = find_regexp(regexp_method_send_node)
regexp = find_regexp(regexp_method_send_node, block_node)
register_offense(node, block_node, regexp)
end

Expand Down Expand Up @@ -119,10 +119,11 @@ def extract_send_node(block_node)
regexp_method_send_node
end

def find_regexp(node)
def find_regexp(node, block)
return node.child_nodes.first if node.match_with_lvasgn_type?

if node.receiver.lvar_type?
if node.receiver.lvar_type? &&
(block.numblock_type? || node.receiver.source == block.arguments.first.source)
node.first_argument
elsif node.first_argument.lvar_type?
node.receiver
Expand Down
26 changes: 26 additions & 0 deletions spec/rubocop/cop/style/select_by_regexp_spec.rb
Expand Up @@ -38,6 +38,19 @@
RUBY
end

it 'registers an offense and corrects for `blockvar =~ lvar`' do
expect_offense(<<~RUBY, method: method)
lvar = /regexp/
array.#{method} { |x| x =~ lvar }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^ #{message}
RUBY

expect_correction(<<~RUBY)
lvar = /regexp/
array.#{correction}(lvar)
RUBY
end

it 'registers an offense and corrects for `regexp =~ blockvar`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { |x| /regexp/ =~ x }
Expand All @@ -49,6 +62,19 @@
RUBY
end

it 'registers an offense and corrects for `lvar =~ blockvar`' do
expect_offense(<<~RUBY, method: method)
lvar = /regexp/
array.#{method} { |x| lvar =~ x }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^ #{message}
RUBY

expect_correction(<<~RUBY)
lvar = /regexp/
array.#{correction}(lvar)
RUBY
end

it 'registers an offense and corrects when there is no explicit regexp' do
expect_offense(<<~RUBY, method: method)
array.#{method} { |x| x =~ y }
Expand Down