Skip to content

Commit

Permalink
[Fix #7712] Fix an incorrect autocorrect for Style/OrAssignment
Browse files Browse the repository at this point in the history
Fixes #7712.

This PR fixes an incorrect autocorrect for `Style/OrAssignment`
when using `elsif` branch.

The following is a reproduction procedure.

```ruby
% cat example.rb
foo = if foo
        foo
      elsif
        bar
      else
        'default'
      end
```

It is changed to the code with syntax error as follows.

```console
% bundle exec rubocop -a --only Style/OrAssignment
(snip)

% cat example.rb
foo ||= elsif
          bar
        else
         'default'

% ruby -c example.rb
example.rb:1: syntax error, unexpected `elsif'
foo ||= elsif
```

The or assignment operator replaced when using `elsif` branch is complicated.
The PR will accept the above case without offense.
  • Loading branch information
koic authored and bbatsov committed Feb 17, 2020
1 parent 75f5b98 commit 5400c1e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -25,6 +25,7 @@
* [#7688](https://github.com/rubocop-hq/rubocop/issues/7688): Fix a bug in `Style/MethodCallWithArgsParentheses` that made `--auto-gen-config` crash. ([@buehmann][])
* [#7203](https://github.com/rubocop-hq/rubocop/issues/7203): Fix an infinite loop error for `Style/TernaryParentheses` with `Style/RedundantParentheses` when using `EnforcedStyle: require_parentheses_when_complex`. ([@koic][])
* [#7708](https://github.com/rubocop-hq/rubocop/issues/7708): Make it possible to use EOL `rubocop:disable` comments on comment lines. ([@jonas054][])
* [#7712](https://github.com/rubocop-hq/rubocop/issues/7712): Fix an incorrect autocorrect for `Style/OrAssignment` when using `elsif` branch. ([@koic][])

### Changes

Expand Down
5 changes: 3 additions & 2 deletions lib/rubocop/cop/style/or_assignment.rb
Expand Up @@ -34,7 +34,7 @@ class OrAssignment < Cop
(if
({lvar ivar cvar gvar} _var)
({lvar ivar cvar gvar} _var)
_))
$_))
PATTERN

def_node_matcher :unless_assignment?, <<~PATTERN
Expand All @@ -51,7 +51,8 @@ def on_if(node)
end

def on_lvasgn(node)
return unless ternary_assignment?(node)
return unless (else_branch = ternary_assignment?(node))
return if else_branch.if_type?

add_offense(node)
end
Expand Down
14 changes: 14 additions & 0 deletions spec/rubocop/cop/style/or_assignment_spec.rb
Expand Up @@ -321,4 +321,18 @@
RUBY
end
end

context 'when using `elsif` statement' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo = if foo
foo
elsif
bar
else
'default'
end
RUBY
end
end
end

0 comments on commit 5400c1e

Please sign in to comment.