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 an error for Style/NegatedIfElseCondition #11646

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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11646](https://github.com/rubocop/rubocop/pull/11646): Fix an error for `Style/NegatedIfElseCondition` when using `()` as a condition. ([@koic][])
17 changes: 11 additions & 6 deletions lib/rubocop/cop/style/negated_if_else_condition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,11 @@ def on_new_investigation

def on_if(node)
return unless if_else?(node)

condition = unwrap_begin_nodes(node.condition)

return unless (condition = unwrap_begin_nodes(node.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|
message = message(node)
add_offense(node, message: message) do |corrector|
unless corrected_ancestor?(node)
correct_negated_condition(corrector, condition)
swap_branches(corrector, node)
Expand All @@ -73,7 +71,8 @@ def if_else?(node)
end

def unwrap_begin_nodes(node)
node = node.children.first while node.begin_type? || node.kwbegin_type?
node = node.children.first while node && (node.begin_type? || node.kwbegin_type?)

node
end

Expand All @@ -82,6 +81,12 @@ def negated_condition?(node)
(node.negation_method? || NEGATED_EQUALITY_METHODS.include?(node.method_name))
end

def message(node)
type = node.ternary? ? 'ternary' : 'if-else'

format(MSG, type: type)
end

def corrected_ancestor?(node)
node.each_ancestor(:if).any? { |ancestor| @corrected_nodes&.include?(ancestor) }
end
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 @@ -229,6 +229,16 @@
RUBY
end

it 'does not crash when using `()` as a condition' do
expect_no_offenses(<<~RUBY)
if ()
foo
else
bar
end
RUBY
end

it 'moves comments to correct branches during autocorrect' do
expect_offense(<<~RUBY)
if !condition.nil?
Expand Down