Skip to content

Commit

Permalink
Fix false positives for Style/EndlessMethod
Browse files Browse the repository at this point in the history
Follow-up to #13874 (comment)

This PR fixes false positives for `Style/EndlessMethod` when using assignment method definitions.

Setter methods cannot be defined as endless methods.

```console
$ ruby -vc -e "def foo=(arg) = bar"
ruby 3.4.2 (2025-02-15 revision d2930f8e7a) +PRISM [x86_64-darwin23]
ruby: -e:1: syntax error found (SyntaxError)
> 1 | def foo=(arg) = bar
    |     ^~~~ invalid method name; a setter method cannot be defined in an endless method definition
```
  • Loading branch information
koic authored and bbatsov committed Feb 26, 2025
1 parent cc6da5c commit 7d4f115
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/fix_false_positives_for_style_endless_method.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#13910](https://github.com/rubocop/rubocop/pull/13910): Fix false positives for `Style/EndlessMethod` when using setter method definitions. ([@koic][])
2 changes: 2 additions & 0 deletions lib/rubocop/cop/style/endless_method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ class EndlessMethod < Base
MSG_REQUIRE_ALWAYS = 'Use endless method definitions.'

def on_def(node)
return if node.assignment_method?

case style
when :allow_single_line, :allow_always
handle_allow_style(node)
Expand Down
18 changes: 18 additions & 0 deletions spec/rubocop/cop/style/endless_method_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,14 @@ def my_method = x
RUBY
end

it 'does not register an offense for a single line setter method' do
expect_no_offenses(<<~RUBY)
def my_method=(arg)
arg.foo
end
RUBY
end

it 'does not register an offense when the endless version excess Metrics/MaxLineLength[Max]' do
expect_no_offenses(<<~RUBY)
def my_method
Expand Down Expand Up @@ -392,6 +400,16 @@ def my_method = x.foo
RUBY
end

it 'does not register an offense for a multiline setter method' do
expect_no_offenses(<<~RUBY)
def my_method=(arg)
x.foo
.bar
.baz
end
RUBY
end

it 'does not register an offense when the endless version excess Metrics/MaxLineLength[Max]' do
expect_no_offenses(<<~RUBY)
def my_method
Expand Down

0 comments on commit 7d4f115

Please sign in to comment.