From 9ffcb57042cfcd38869f491197004cb49dc2a37b Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Wed, 6 May 2020 18:18:40 +0900 Subject: [PATCH] [Fix #7928] Fix a false positive for `Style/GuardClause` Fixes #7928. This PR fixes a false positive for `Style/GuardClause` when assigning the result of a guard condition with `else`. --- CHANGELOG.md | 1 + lib/rubocop/cop/style/guard_clause.rb | 3 ++- spec/rubocop/cop/style/guard_clause_spec.rb | 13 +++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 856f84891bc..05278ddc3d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/rubocop/cop/style/guard_clause.rb b/lib/rubocop/cop/style/guard_clause.rb index 5c0b27ad8f0..55060d6bb2c 100644 --- a/lib/rubocop/cop/style/guard_clause.rb +++ b/lib/rubocop/cop/style/guard_clause.rb @@ -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) diff --git a/spec/rubocop/cop/style/guard_clause_spec.rb b/spec/rubocop/cop/style/guard_clause_spec.rb index 362bed3e726..fe763bdd8d9 100644 --- a/spec/rubocop/cop/style/guard_clause_spec.rb +++ b/spec/rubocop/cop/style/guard_clause_spec.rb @@ -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 }