Skip to content

Commit

Permalink
Fix an incorrect auto-correct for Style/SingleLineMethods
Browse files Browse the repository at this point in the history
Fix the following incorrect auto-correct for `Style/SingleLineMethods`
when using single line class method definition.

```console
% cat example.rb
def self.some_method; body end

% rubocop --only Style/SingleLineMethods -a
(snip)

Offenses:

example.rb:1:1: C: [Corrected] Style/SingleLineMethods: Avoid
single-line method definitions.
def self.some_method; body end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense corrected
```

## Before

```console
% cat example.rb
def some_method() = body
```

`self` is lost due to auto-correction.

## After

```console
% cat example.rb
def self.some_method() = body
```
  • Loading branch information
koic committed Mar 29, 2021
1 parent 464c4df commit cf166e2
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 1 deletion.
@@ -0,0 +1 @@
* [#9645](https://github.com/rubocop/rubocop/pull/9645): Fix an incorrect auto-correct for `Style/SingleLineMethods` when using single line class method definition. ([@koic][])
3 changes: 2 additions & 1 deletion lib/rubocop/cop/style/single_line_methods.rb
Expand Up @@ -91,8 +91,9 @@ def correct_to_multiline(corrector, node)
end

def correct_to_endless(corrector, node)
self_receiver = node.self_receiver? ? 'self.' : ''
arguments = node.arguments.any? ? node.arguments.source : '()'
replacement = "def #{node.method_name}#{arguments} = #{node.body.source}"
replacement = "def #{self_receiver}#{node.method_name}#{arguments} = #{node.body.source}"
corrector.replace(node, replacement)
end

Expand Down
6 changes: 6 additions & 0 deletions spec/rubocop/cop/style/single_line_methods_spec.rb
Expand Up @@ -168,6 +168,12 @@ def some_method() = body
RUBY
end

it 'corrects to an endless class method definition' do
expect_correction(<<~RUBY.strip, source: 'def self.some_method; body end')
def self.some_method() = body
RUBY
end

it 'retains comments' do
source = 'def some_method; body end # comment'
expect_correction(<<~RUBY.strip, source: source)
Expand Down

0 comments on commit cf166e2

Please sign in to comment.