Skip to content

Commit

Permalink
[Fix #10216] Fix an incorrect autocorrect for Style/SelectByRegexp
Browse files Browse the repository at this point in the history
Fix #10216.

This PR fixes an incorrect autocorrect for `Style/SelectByRegexp`
when using `lvar =~ blockvar` in a block.
  • Loading branch information
koic authored and bbatsov committed Oct 27, 2021
1 parent e93f705 commit 6f92906
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
@@ -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

0 comments on commit 6f92906

Please sign in to comment.