Skip to content

Commit

Permalink
[Fix #10321] Make Style/MethodDefParentheses aware of anonymous blo…
Browse files Browse the repository at this point in the history
…ck forwarding

Fixes #10321.

This PR fixes a false positive for `Style/MethodDefParentheses` when using
`EnforcedStyle: require_no_parentheses` and Ruby 3.1's anonymous block forwarding.
  • Loading branch information
koic authored and bbatsov committed Dec 29, 2021
1 parent 883bf10 commit 6821569
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#10321](https://github.com/rubocop/rubocop/issues/10321): Make `Style/MethodDefParentheses` aware of Ruby 3.1's anonymous block forwarding. ([@koic][])
19 changes: 15 additions & 4 deletions lib/rubocop/cop/style/method_def_parentheses.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ module Style
# This cop checks for parentheses around the arguments in method
# definitions. Both instance and class/singleton methods are checked.
#
# This cop does not consider endless methods, since parentheses are
# always required for them.
# Regardless of style, parentheses are necessary for:
#
# 1. Endless methods
# 2. Argument lists containing a `forward-arg` (`...`)
# 3. Argument lists containing an anonymous block forwarding (`&`)
#
# Removing the parens would be a syntax error here.
#
# @example EnforcedStyle: require_parentheses (default)
# # The `require_parentheses` style requires method definitions
Expand Down Expand Up @@ -133,9 +138,9 @@ def forced_parentheses?(node)
# Regardless of style, parentheses are necessary for:
# 1. Endless methods
# 2. Argument lists containing a `forward-arg` (`...`)
# 3. Argument lists containing an anonymous block forwarding (`&`)
# Removing the parens would be a syntax error here.

node.endless? || node.arguments.any?(&:forward_arg_type?)
node.endless? || node.arguments.any?(&:forward_arg_type?) || anonymous_block_arg?(node)
end

def require_parentheses?(args)
Expand Down Expand Up @@ -163,6 +168,12 @@ def unwanted_parentheses(args)
unexpected_style_detected 'require_parentheses'
end
end

def anonymous_block_arg?(node)
return false unless (last_argument = node.arguments.last)

last_argument.blockarg_type? && last_argument.name.nil?
end
end
end
end
Expand Down
8 changes: 8 additions & 0 deletions spec/rubocop/cop/style/method_def_parentheses_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,14 @@ def foo(...)
end
RUBY
end

it 'requires parens for anonymous block forwarding', :ruby31 do
expect_no_offenses(<<~RUBY)
def foo(&)
bar(&)
end
RUBY
end
end

shared_examples 'endless methods' do
Expand Down

0 comments on commit 6821569

Please sign in to comment.