Skip to content

Commit

Permalink
Merge pull request rubocop#12202 from ydah/fix-incorrect-autocorrect-…
Browse files Browse the repository at this point in the history
…redundant-conditional

Fix an incorrect autocorrect for `Style/RedundantConditional` when unless/else with boolean results
  • Loading branch information
koic committed Sep 12, 2023
2 parents 1b7da81 + cd5d1f5 commit 7ad9d85
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 9 deletions.
@@ -0,0 +1 @@
* [#12202](https://github.com/rubocop/rubocop/pull/12202): Fix an incorrect autocorrect for `Style/RedundantConditional` when unless/else with boolean results. ([@ydah][])
10 changes: 1 addition & 9 deletions lib/rubocop/cop/style/redundant_conditional.rb
Expand Up @@ -70,19 +70,11 @@ def offense?(node)

def replacement_condition(node)
condition = node.condition.source
expression = invert_expression?(node) ? "!(#{condition})" : condition
expression = redundant_condition_inverted?(node) ? "!(#{condition})" : condition

node.elsif? ? indented_else_node(expression, node) : expression
end

def invert_expression?(node)
(
(node.if? || node.elsif? || node.ternary?) && redundant_condition_inverted?(node)
) || (
node.unless? && redundant_condition?(node)
)
end

def indented_else_node(expression, node)
"else\n#{indentation(node)}#{expression}"
end
Expand Down
30 changes: 30 additions & 0 deletions spec/rubocop/cop/style/redundant_conditional_spec.rb
Expand Up @@ -57,6 +57,36 @@
RUBY
end

it 'registers an offense for unless/else with boolean results' do
expect_offense(<<~RUBY)
unless x == y
^^^^^^^^^^^^^ This conditional expression can just be replaced by `!(x == y)`.
true
else
false
end
RUBY

expect_correction(<<~RUBY)
!(x == y)
RUBY
end

it 'registers an offense for unless/else with negated boolean results' do
expect_offense(<<~RUBY)
unless x == y
^^^^^^^^^^^^^ This conditional expression can just be replaced by `x == y`.
false
else
true
end
RUBY

expect_correction(<<~RUBY)
x == y
RUBY
end

it 'registers an offense for if/elsif/else with boolean results' do
expect_offense(<<~RUBY)
if cond
Expand Down

0 comments on commit 7ad9d85

Please sign in to comment.