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 an error for Style/SelectByRegexp #11348

Merged
merged 1 commit into from Dec 30, 2022
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
1 change: 1 addition & 0 deletions changelog/fix_error_for_style_select_by_regexp.md
@@ -0,0 +1 @@
* [#11348](https://github.com/rubocop/rubocop/pull/11348): Fix an error for `Style/SelectByRegexp` when block body is empty. ([@koic][])
8 changes: 6 additions & 2 deletions lib/rubocop/cop/style/select_by_regexp.rb
Expand Up @@ -86,12 +86,12 @@ class SelectByRegexp < Base

def on_send(node)
return unless (block_node = node.block_node)
return if block_node.body.begin_type?
return if block_node.body&.begin_type?
return if receiver_allowed?(block_node.receiver)
return unless (regexp_method_send_node = extract_send_node(block_node))
return if match_predicate_without_receiver?(regexp_method_send_node)

opposite = regexp_method_send_node.send_type? && regexp_method_send_node.method?(:!~)
opposite = opposite?(regexp_method_send_node)
regexp = find_regexp(regexp_method_send_node, block_node)

register_offense(node, block_node, regexp, opposite)
Expand Down Expand Up @@ -128,6 +128,10 @@ def extract_send_node(block_node)
regexp_method_send_node
end

def opposite?(regexp_method_send_node)
regexp_method_send_node.send_type? && regexp_method_send_node.method?(:!~)
end

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

Expand Down
6 changes: 6 additions & 0 deletions spec/rubocop/cop/style/select_by_regexp_spec.rb
Expand Up @@ -150,6 +150,12 @@
RUBY
end

it 'does not register an offense when the block body is empty' do
expect_no_offenses(<<~RUBY)
array.#{method} { }
RUBY
end

it 'registers an offense and corrects without a receiver' do
expect_offense(<<~RUBY, method: method)
#{method} { |x| x.match?(/regexp/) }
Expand Down