From de12994aa4a414d5e88f4ca8aa8b983335b331f5 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sun, 16 Feb 2020 10:45:48 +0900 Subject: [PATCH] [Fix #7712] Fix an incorrect autocorrect for `Style/OrAssignment` 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. --- CHANGELOG.md | 1 + lib/rubocop/cop/style/or_assignment.rb | 5 +++-- spec/rubocop/cop/style/or_assignment_spec.rb | 14 ++++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e056ea33b35..792e073a307 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/rubocop/cop/style/or_assignment.rb b/lib/rubocop/cop/style/or_assignment.rb index d7d8272f43a..fe3df4a73fe 100644 --- a/lib/rubocop/cop/style/or_assignment.rb +++ b/lib/rubocop/cop/style/or_assignment.rb @@ -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 @@ -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 diff --git a/spec/rubocop/cop/style/or_assignment_spec.rb b/spec/rubocop/cop/style/or_assignment_spec.rb index fe0334ae09b..7ec9df90fcc 100644 --- a/spec/rubocop/cop/style/or_assignment_spec.rb +++ b/spec/rubocop/cop/style/or_assignment_spec.rb @@ -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