Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix #9050] Fix a false positive for Style/NegatedIfElseCondition #9051

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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