Skip to content

Commit

Permalink
Fix a false positive for Layout/SpaceAroundOperators
Browse files Browse the repository at this point in the history
This PR fixes a false positive for `Layout/SpaceAroundOperators`
when match operators between `<<` and `+=`.

This change makes the following behavior consistent:

## before

Does not register an offense when aligned between `<<`.

```consle
% cat example.rb
# It does not register an offense.
x  << foo
yz << bar
```

An offense is registered when either is updated to `+=`.

```console
% cat example.rb
# It does not register an offense.
x  << foo
yz += bar

% bundle exec rubocop --only Layout/SpaceAroundOperators
(snip)

example.rb:2:4: C: [Correctable] Layout/SpaceAroundOperators: Operator
<< should be surrounded by a single space.
x  << foo
^^

1 file inspected, 1 offense detected, 1 offense auto-correctable
```

## After

Both does not register an offense.
  • Loading branch information
koic authored and bbatsov committed Aug 29, 2021
1 parent 9885eef commit 9db1c7d
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
@@ -0,0 +1 @@
* [#10054](https://github.com/rubocop/rubocop/pull/10054): Fix a false positive for `Layout/SpaceAroundOperators` when match operators between `<<` and `+=`. ([@koic][])
8 changes: 7 additions & 1 deletion lib/rubocop/cop/mixin/preceding_following_alignment.rb
Expand Up @@ -93,7 +93,13 @@ def aligned_char?(range, line)
end

def aligned_assignment?(range, line)
range.source[-1] == '=' && line[range.last_column - 1] == '='
range.source[-1] == '=' && line[range.last_column - 1] == '=' ||
aligned_with_append_operator?(range, line)
end

def aligned_with_append_operator?(range, line)
range.source == '<<' && line[range.last_column - 1] == '=' ||
range.source[-1] == '=' && line[(range.last_column - 2)..(range.last_column - 1)] == '<<'
end

def aligned_identical?(range, line)
Expand Down
14 changes: 14 additions & 0 deletions spec/rubocop/cop/layout/space_around_operators_spec.rb
Expand Up @@ -858,6 +858,20 @@ class ShowSourceTestClass < ShowSourceTestSuperClass
RUBY
end

it 'does not register an offenses match operators between `<<` and `+=`' do
expect_no_offenses(<<~RUBY)
x << foo
yz += bar
RUBY
end

it 'does not register an offenses match operators between `+=` and `<<`' do
expect_no_offenses(<<~RUBY)
x += foo
yz << bar
RUBY
end

it 'registers an offense and corrects various assignments with too many spaces' do
expect_offense(<<~RUBY)
x ||= 0
Expand Down

0 comments on commit 9db1c7d

Please sign in to comment.