Skip to content

Commit

Permalink
[Fix #10421] Make Style/DefWithParentheses aware of endless method …
Browse files Browse the repository at this point in the history
…definition

Fixes #10421.

This PR makes `Style/DefWithParentheses` aware of endless method definition.

`def foo() do_something end` will continue to allow because `def foo do_something end`
is a syntax error.
On the other hand, be aware that the endless method definition's parentheses can be omitted.
  • Loading branch information
koic authored and bbatsov committed Feb 20, 2022
1 parent fee162c commit aa47871
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
@@ -0,0 +1 @@
* [#10421](https://github.com/rubocop/rubocop/issues/10421): Make `Style/DefWithParentheses` aware of endless method definition. ([@koic][])
20 changes: 13 additions & 7 deletions lib/rubocop/cop/style/def_with_parentheses.rb
Expand Up @@ -11,35 +11,41 @@ module Style
#
# # bad
# def foo()
# # does a thing
# do_something
# end
#
# # good
# def foo
# # does a thing
# do_something
# end
#
# # also good
# def foo() does_a_thing end
# # bad
# def foo() = do_something
#
# # good
# def foo = do_something
#
# # good (without parentheses it's a syntax error)
# def foo() do_something end
#
# @example
#
# # bad
# def Baz.foo()
# # does a thing
# do_something
# end
#
# # good
# def Baz.foo
# # does a thing
# do_something
# end
class DefWithParentheses < Base
extend AutoCorrector

MSG = "Omit the parentheses in defs when the method doesn't accept any arguments."

def on_def(node)
return if node.single_line?
return if node.single_line? && !node.endless?
return unless !node.arguments? && (node_arguments = node.arguments.source_range)

add_offense(node_arguments) do |corrector|
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/style/def_with_parentheses_spec.rb
Expand Up @@ -29,6 +29,19 @@ def Test.func
RUBY
end

context 'Ruby >= 3.0', :ruby30 do
it 'reports an offense for endless method definition with empty parens' do
expect_offense(<<~RUBY)
def foo() = do_something
^^ Omit the parentheses in defs when the method doesn't accept any arguments.
RUBY

expect_correction(<<~RUBY)
def foo = do_something
RUBY
end
end

it 'accepts def with arg and parens' do
expect_no_offenses(<<~RUBY)
def func(a)
Expand Down

0 comments on commit aa47871

Please sign in to comment.