Skip to content

Commit

Permalink
[Fix #9603] Fix a false positive for Style/SoleNestedConditional
Browse files Browse the repository at this point in the history
Fixes #9603.

This PR fixes a false positive for `Style/SoleNestedConditional`
when using nested modifier on value assigned in condition.
  • Loading branch information
koic authored and bbatsov committed Mar 16, 2021
1 parent 1d4959d commit 7b90985
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
@@ -0,0 +1 @@
* [#9603](https://github.com/rubocop/rubocop/issues/9603): Fix a false positive for `Style/SoleNestedConditional` when using nested modifier on value assigned in condition. ([@koic][])
16 changes: 16 additions & 0 deletions lib/rubocop/cop/style/sole_nested_conditional.rb
Expand Up @@ -43,6 +43,7 @@ def on_if(node)
return if node.ternary? || node.else? || node.elsif?

if_branch = node.if_branch
return if use_variable_assignment_in_condition?(node.condition, if_branch)
return unless offending_branch?(if_branch)

message = format(MSG, conditional_type: node.keyword)
Expand All @@ -53,6 +54,21 @@ def on_if(node)

private

def use_variable_assignment_in_condition?(condition, if_branch)
assigned_variables = assigned_variables(condition)

assigned_variables && if_branch&.if_type? &&
assigned_variables.include?(if_branch.condition.source)
end

def assigned_variables(condition)
assigned_variables = condition.assignment? ? [condition.children.first.to_s] : []

assigned_variables + condition.descendants.select(&:assignment?).map do |node|
node.children.first.to_s
end
end

def offending_branch?(branch)
return false unless branch

Expand Down
16 changes: 16 additions & 0 deletions spec/rubocop/cop/style/sole_nested_conditional_spec.rb
Expand Up @@ -428,6 +428,22 @@ def foo
RUBY
end

it 'does not register an offense when using nested modifier on value assigned in single condition' do
expect_no_offenses(<<~RUBY)
if var = foo
do_something if var
end
RUBY
end

it 'does not register an offense when using nested modifier on value assigned in multiple conditions' do
expect_no_offenses(<<~RUBY)
if cond && var = foo
do_something if var
end
RUBY
end

context 'when the inner condition has a send node without parens' do
context 'in guard style' do
it 'registers an offense and corrects' do
Expand Down

0 comments on commit 7b90985

Please sign in to comment.