Skip to content

Commit

Permalink
[Fix rubocop#9050] Fix a false positive for `Style/NegatedIfElseCondi…
Browse files Browse the repository at this point in the history
…tion`

Fixes rubocop#9050.

This PR fixes a false positive for `Style/NegatedIfElseCondition`
when `if` with `!!` condition.
  • Loading branch information
koic committed Nov 15, 2020
1 parent 1905f1b commit c5b9552
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#9050](https://github.com/rubocop-hq/rubocop/issues/9050): Fix a false positive for `Style/NegatedIfElseCondition` when `if` with `!!` condition. ([@koic][])
4 changes: 3 additions & 1 deletion lib/rubocop/cop/style/negated_if_else_condition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ class NegatedIfElseCondition < Base

NEGATED_EQUALITY_METHODS = %i[!= !~].freeze

def_node_matcher :double_negation?, '(send (send _ :!) :!)'

def self.autocorrect_incompatible_with
[Style::InverseMethods, Style::Not]
end
Expand All @@ -47,7 +49,7 @@ def on_if(node)
return unless if_else?(node)

condition = node.condition
return unless negated_condition?(condition)
return if double_negation?(condition) || !negated_condition?(condition)

type = node.ternary? ? 'ternary' : 'if-else'
add_offense(node, message: format(MSG, type: type)) do |corrector|
Expand Down
10 changes: 10 additions & 0 deletions spec/rubocop/cop/style/negated_if_else_condition_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,16 @@
RUBY
end

it 'does not register an offense when `if` with `!!` condition' do
expect_no_offenses(<<~RUBY)
if !!x
do_something
else
do_another_thing
end
RUBY
end

it 'does not register an offense when `if` with negated condition has no `else` branch' do
expect_no_offenses(<<~RUBY)
if !x
Expand Down

0 comments on commit c5b9552

Please sign in to comment.