Skip to content

Commit

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

This PR fixes a false positive for `Style/UnlessLogicalOperators`
when using `||` operator and invoked method name includes "or"
in the conditional branch.

This is an issue due to string matching of source code instead of AST.
  • Loading branch information
koic authored and bbatsov committed Mar 1, 2021
1 parent 0597fb9 commit 6d8664c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
@@ -0,0 +1 @@
* [#9551](https://github.com/rubocop/rubocop/issues/9551): Fix a false positive for `Style/UnlessLogicalOperators` when using `||` operator and invoked method name includes "or" in the conditional branch. ([@koic][])
10 changes: 8 additions & 2 deletions lib/rubocop/cop/style/unless_logical_operators.rb
Expand Up @@ -87,11 +87,17 @@ def mixed_logical_operator?(node)
end

def mixed_precedence_and?(node)
node.source.include?('&&') && node.source.include?('and')
and_sources = node.condition.each_descendant(:and).map(&:operator)
and_sources << node.condition.operator if node.condition.and_type?

!(and_sources.all? { |s| s == '&&' } || and_sources.all? { |s| s == 'and' })
end

def mixed_precedence_or?(node)
node.source.include?('||') && node.source.include?('or')
or_sources = node.condition.each_descendant(:or).map(&:operator)
or_sources << node.condition.operator if node.condition.or_type?

!(or_sources.all? { |s| s == '||' } || or_sources.all? { |s| s == 'or' })
end
end
end
Expand Down
20 changes: 20 additions & 0 deletions spec/rubocop/cop/style/unless_logical_operators_spec.rb
Expand Up @@ -116,6 +116,26 @@ def condition?
return unless a?
RUBY
end

it 'does not register an offense when using `||` operator and invoked method name includes "or" in the conditional branch' do
expect_no_offenses(<<~RUBY)
unless condition
includes_or_in_the_name
foo || bar
end
RUBY
end

it 'does not register an offense when using `&&` operator and invoked method name includes "and" in the conditional branch' do
expect_no_offenses(<<~RUBY)
unless condition
includes_and_in_the_name
foo && bar
end
RUBY
end
end

context 'EnforcedStyle is `forbid_logical_operators`' do
Expand Down

0 comments on commit 6d8664c

Please sign in to comment.