Skip to content

Commit

Permalink
[Fix rubocop#162] Fix a false positive for `Performance/RedundantBloc…
Browse files Browse the repository at this point in the history
…kCall`

Fixes rubocop#162.

This PR fixes a false positive for `Performance/RedundantBlockCall`
when an optional block that is overridden by block variable.
  • Loading branch information
koic committed Mar 2, 2021
1 parent a028583 commit 6b30e47
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#162](https://github.com/rubocop/rubocop-performance/issues/162): Fix a false positive for `Performance/RedundantBlockCall` when an optional block that is overridden by block variable. ([@koic][])

## 1.10.1 (2021-03-02)

### Bug fixes
Expand Down
8 changes: 7 additions & 1 deletion lib/rubocop/cop/performance/redundant_block_call.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def autocorrect(corrector, node)
end

def calls_to_report(argname, body)
return [] if blockarg_assigned?(body, argname)
return [] if blockarg_assigned?(body, argname) || shadowed_block_argument?(body, argname)

blockarg_calls(body, argname).map do |call|
return [] if args_include_block_pass?(call)
Expand All @@ -87,6 +87,12 @@ def calls_to_report(argname, body)
end
end

def shadowed_block_argument?(body, block_argument_of_method_signature)
return false unless body.block_type?

body.arguments.map(&:source).include?(block_argument_of_method_signature.to_s)
end

def args_include_block_pass?(blockcall)
_receiver, _call, *args = *blockcall

Expand Down
31 changes: 30 additions & 1 deletion spec/rubocop/cop/performance/redundant_block_call_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def method(&block)
RUBY
end

it 'accepts an optional block that is overridden' do
it 'accepts an optional block that is overridden by local variable' do
expect_no_offenses(<<~RUBY)
def method(&block)
block = ->(i) { puts i }
Expand All @@ -126,6 +126,35 @@ def method(&block)
RUBY
end

it 'accepts an optional block that is overridden by block variable' do
expect_no_offenses(<<~RUBY)
def method(&block)
->(i) { puts i }.then do |block|
block.call(1)
end
end
RUBY
end

it 'registers an offense when an optional block that is not overridden by block variable' do
expect_offense(<<~RUBY)
def method(&block)
->(i) { puts i }.then do |_block|
block.call(1)
^^^^^^^^^^^^^ Use `yield` instead of `block.call`.
end
end
RUBY

expect_correction(<<~RUBY)
def method(&block)
->(i) { puts i }.then do |_block|
yield(1)
end
end
RUBY
end

it 'formats the error message for func.call(1) correctly' do
expect_offense(<<~RUBY)
def method(&func)
Expand Down

0 comments on commit 6b30e47

Please sign in to comment.