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 #12687] Fix a false positive for Lint/Void #12688

Merged
merged 1 commit into from
Feb 15, 2024
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
1 change: 1 addition & 0 deletions changelog/fix_false_positive_for_lint_void.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12687](https://github.com/rubocop/rubocop/issues/12687): Fix a false positive for `Lint/Void` when `each` block with conditional expressions that has multiple statements. ([@koic][])
7 changes: 6 additions & 1 deletion lib/rubocop/cop/lint/void.rb
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,12 @@ def check_begin(node)
expressions = *node
expressions.pop unless in_void_context?(node)
expressions.each do |expr|
check_void_op(expr)
check_void_op(expr) do
block_node = node.each_ancestor(:block).first

block_node&.method?(:each)
end

check_expression(expr)
end
end
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/lint/void_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -614,6 +614,18 @@ def foo=(rhs)
RUBY
end

it 'does not register `#each` block with conditional expressions that has multiple statements' do
expect_no_offenses(<<~RUBY)
enumerator_as_filter.each do |item|
Copy link
Collaborator

Choose a reason for hiding this comment

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

Won't this be different for this different enumerators, though? Maybe some Allowed list would make more sense than just assuming that multiple expressions are OK all the time.

Copy link
Member Author

Choose a reason for hiding this comment

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

Initially, I also considered Allowed list approach, but it appears that the issue was simply that the following logic for on_block was not accounted for in the implementation of on_begin.
https://github.com/rubocop/rubocop/blob/v1.60.2/lib/rubocop/cop/lint/void.rb#L86

So, I think this approach could provide a more generic solution instead of Allowed list.

puts item

# The `filter` method is used to filter for matches with `42`.
# In this case, it's not void.
item == 42
end
RUBY
end

context 'Ruby 2.7', :ruby27 do
it 'registers two offenses for void literals in `#tap` method' do
expect_offense(<<~RUBY)
Expand Down