Skip to content

Commit

Permalink
Fix a false positive for Layout/SpaceAroundMethodCallOperator
Browse files Browse the repository at this point in the history
This PR fixes the following false positive for
`Layout/SpaceAroundMethodCallOperator` cop when there is
a space between `.` operator and a comment.

```ruby
foo. # comment
  bar.baz
```

```console
% rubocop --only Layout/SpaceAroundMethodCallOperator
(snip)

Inspecting 1 file
C

Offenses:

example.rb:1:5: C: Layout/SpaceAroundMethodCallOperator: Avoid using
spaces around a method call operator.
foo. # comment
    ^

1 file inspected, 1 offense detected
```

Also this PR does not add to the changelog entry because
`Layout/SpaceAroundMethodCallOperator` cop has not been released yet.
  • Loading branch information
koic authored and bbatsov committed Apr 15, 2020
1 parent b54bb91 commit fc24294
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/rubocop/cop/layout/space_around_method_call_operator.rb
Expand Up @@ -72,7 +72,7 @@ def check_and_add_offense(node, add_left_offense = true)
left = previous_token(operator)
right = next_token(operator)

if valid_right_token?(right, operator)
if !right.comment? && valid_right_token?(right, operator)
no_space_offenses(node, operator, right, MSG)
end
return unless valid_left_token?(left, operator)
Expand Down Expand Up @@ -121,7 +121,9 @@ def left_token_for_auto_correction(node, operator)

def right_token_for_auto_correction(operator)
right_token = next_token(operator)
return right_token if valid_right_token?(right_token, operator)
if !right_token.comment? && valid_right_token?(right_token, operator)
return right_token
end

operator
end
Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/layout/space_around_method_call_operator_spec.rb
Expand Up @@ -177,6 +177,28 @@
foo.bar.buzz
RUBY
end

context 'when there is a space between `.` operator and a comment' do
it 'does not register an offense when there is not a space before `.`' do
expect_no_offenses(<<~RUBY)
foo. # comment
bar.baz
RUBY
end

it 'registers an offense when there is a space before `.`' do
expect_offense(<<~RUBY)
foo . # comment
^ Avoid using spaces around a method call operator.
bar.baz
RUBY

expect_correction(<<~RUBY)
foo. # comment
bar.baz
RUBY
end
end
end

context 'safe navigation operator' do
Expand Down

0 comments on commit fc24294

Please sign in to comment.