Skip to content

Commit

Permalink
[Fix rubocop#12571] Fix false posives for Naming/BlockForwarding
Browse files Browse the repository at this point in the history
Fixes rubocop#12571.

This PR fixes false positives for `Naming/BlockForwarding`
when using explicit block forwarding in block method.
  • Loading branch information
koic committed Dec 28, 2023
1 parent 229f205 commit 17d5f46
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/rubocop/cop/naming/block_forwarding.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,21 +51,29 @@ def self.autocorrect_incompatible_with
[Lint::AmbiguousOperator, Style::ArgumentsForwarding]
end

# rubocop:disable Metrics/CyclomaticComplexity
def on_def(node)
return if node.arguments.empty?

last_argument = node.last_argument
return if expected_block_forwarding_style?(node, last_argument)

register_offense(last_argument, node)

invalid_syntax = false
node.each_descendant(:block_pass) do |block_pass_node|
next if block_pass_node.children.first&.sym_type? ||
last_argument.source != block_pass_node.source

if block_pass_node.each_ancestor(:block, :numblock).any?
invalid_syntax = true
next
end

register_offense(block_pass_node, node)
end

register_offense(last_argument, node) unless invalid_syntax
end
# rubocop:enable Metrics/CyclomaticComplexity
alias on_defs on_def

private
Expand Down
47 changes: 47 additions & 0 deletions spec/rubocop/cop/naming/block_forwarding_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,53 @@ def foo(k: v, &block)
RUBY
end

it 'does not register an offense when using explicit block forwarding in block method' do
# Prevents the following syntax error:
#
# # foo.rb
# def foo(&)
# block_method do
# bar(&)
# end
# end
#
# $ ruby -vc foo.rb
# ruby 3.3.0 (2023-12-25 revision 5124f9ac75) [x86_64-darwin22]
# foo.rb: foo.rb:4: anonymous block parameter is also used within block (SyntaxError)
#
expect_no_offenses(<<~RUBY)
def foo(&block)
block_method do
bar(&block)
end
end
RUBY
end

it 'does not register an offense when using explicit block forwarding in numbered block method' do
# Prevents the following syntax error:
#
# # foo.rb
# def foo(&)
# block_method do
# bar(&)
# end
# end
#
# $ ruby -vc foo.rb
# ruby 3.3.0 (2023-12-25 revision 5124f9ac75) [x86_64-darwin22]
# foo.rb: foo.rb:4: anonymous block parameter is also used within block (SyntaxError)
#
expect_no_offenses(<<~RUBY)
def foo(&block)
block_method do
bar(&block)
baz(_1)
end
end
RUBY
end

it 'does not register an offense when defining no arguments method' do
expect_no_offenses(<<~RUBY)
def foo
Expand Down

0 comments on commit 17d5f46

Please sign in to comment.