Skip to content

Commit 6821569

Browse files
koicbbatsov
authored andcommitted
[Fix #10321] Make Style/MethodDefParentheses aware of anonymous block 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.
1 parent 883bf10 commit 6821569

File tree

3 files changed

+24
-4
lines changed

3 files changed

+24
-4
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#10321](https://github.com/rubocop/rubocop/issues/10321): Make `Style/MethodDefParentheses` aware of Ruby 3.1's anonymous block forwarding. ([@koic][])

lib/rubocop/cop/style/method_def_parentheses.rb

+15-4
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,13 @@ module Style
66
# This cop checks for parentheses around the arguments in method
77
# definitions. Both instance and class/singleton methods are checked.
88
#
9-
# This cop does not consider endless methods, since parentheses are
10-
# always required for them.
9+
# Regardless of style, parentheses are necessary for:
10+
#
11+
# 1. Endless methods
12+
# 2. Argument lists containing a `forward-arg` (`...`)
13+
# 3. Argument lists containing an anonymous block forwarding (`&`)
14+
#
15+
# Removing the parens would be a syntax error here.
1116
#
1217
# @example EnforcedStyle: require_parentheses (default)
1318
# # The `require_parentheses` style requires method definitions
@@ -133,9 +138,9 @@ def forced_parentheses?(node)
133138
# Regardless of style, parentheses are necessary for:
134139
# 1. Endless methods
135140
# 2. Argument lists containing a `forward-arg` (`...`)
141+
# 3. Argument lists containing an anonymous block forwarding (`&`)
136142
# Removing the parens would be a syntax error here.
137-
138-
node.endless? || node.arguments.any?(&:forward_arg_type?)
143+
node.endless? || node.arguments.any?(&:forward_arg_type?) || anonymous_block_arg?(node)
139144
end
140145

141146
def require_parentheses?(args)
@@ -163,6 +168,12 @@ def unwanted_parentheses(args)
163168
unexpected_style_detected 'require_parentheses'
164169
end
165170
end
171+
172+
def anonymous_block_arg?(node)
173+
return false unless (last_argument = node.arguments.last)
174+
175+
last_argument.blockarg_type? && last_argument.name.nil?
176+
end
166177
end
167178
end
168179
end

spec/rubocop/cop/style/method_def_parentheses_spec.rb

+8
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,14 @@ def foo(...)
9999
end
100100
RUBY
101101
end
102+
103+
it 'requires parens for anonymous block forwarding', :ruby31 do
104+
expect_no_offenses(<<~RUBY)
105+
def foo(&)
106+
bar(&)
107+
end
108+
RUBY
109+
end
102110
end
103111

104112
shared_examples 'endless methods' do

0 commit comments

Comments
 (0)