Skip to content

Commit

Permalink
[Fix rubocop#7928] Fix a false positive for Style/GuardClause
Browse files Browse the repository at this point in the history
Fixes rubocop#7928.

This PR fixes a false positive for `Style/GuardClause`
when assigning the result of a guard condition with `else`.
  • Loading branch information
koic committed May 10, 2020
1 parent 6329595 commit 9ffcb57
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -30,6 +30,7 @@
* [#7909](https://github.com/rubocop-hq/rubocop/pull/7909): Fix a false positive for `Lint/ParenthesesAsGroupedExpression` when using an intended grouped parentheses. ([@koic][])
* [#7913](https://github.com/rubocop-hq/rubocop/pull/7913): Fix a false positive for `Lint/LiteralAsCondition` when using `true` literal in `while` and similar cases. ([@koic][])
* [#7928](https://github.com/rubocop-hq/rubocop/issues/7928): Fix a false message for `Style/GuardClause` when using `and` or `or` operators for guard clause in `then` or `else` branches. ([@koic][])
* [#7928](https://github.com/rubocop-hq/rubocop/issues/7928): Fix a false positive for `Style/GuardClause` when assigning the result of a guard condition with `else`. ([@koic][])

### Changes

Expand Down
3 changes: 2 additions & 1 deletion lib/rubocop/cop/style/guard_clause.rb
Expand Up @@ -126,7 +126,8 @@ def too_long_for_single_line?(node, example)
end

def accepted_form?(node, ending = false)
accepted_if?(node, ending) || node.condition.multiline?
accepted_if?(node, ending) || node.condition.multiline? ||
node.parent&.assignment?
end

def accepted_if?(node, ending)
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/style/guard_clause_spec.rb
Expand Up @@ -197,6 +197,19 @@ def func
RUBY
end

it 'does not register an offense when assigning the result of ' \
'a guard condition with `else`' do
expect_no_offenses(<<~RUBY)
def func
result = if something
work || raise('message')
else
test
end
end
RUBY
end

context 'MinBodyLength: 1' do
let(:cop_config) do
{ 'MinBodyLength' => 1 }
Expand Down

0 comments on commit 9ffcb57

Please sign in to comment.