Class: RuboCop::Cop::DevDoc::Style::LiteralOperatorInCondition

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/dev_doc/style/literal_operator_in_condition.rb

Overview

Flag || between literals in a boolean condition (if, unless, while, until, and ternary). The operator folds to one operand immediately (:a || :b is just :a), so the condition is constant — the branch (or loop body) always runs the same way, and the other literal is dead.

Rationale

if :billing || :payments reads like "either is truthy" but compiles to if :billing — always truthy. The author almost certainly meant a real comparison (==) or a variable, not two literal alternatives. Unlike DevDoc/Style/LiteralOrInWhenClause, a condition has no comma-form alternative, so the right fix depends on intent and is NOT autocorrected — the cop only flags.

Scoped to || only: core Lint/LiteralAsCondition already catches literal && chains and single literals, but misses || chains and ternaries — this cop fills exactly that gap with no overlap.

❌ always truthy — :payments is dead
if :billing || :payments
charge
end

✔️ a real comparison
if status == :billing || status == :payments
charge
end

Examples:

# bad
x = (:a || :b) ? one : two

# good
x = (val == :a || val == :b) ? one : two

Constant Summary collapse

MSG =
'`%<source>s` always evaluates to `%<result>s`, so this condition is constant.'.freeze
LITERAL_TYPES =
%i[sym str int float true false nil].freeze
FALSY_TYPES =
%i[false nil].freeze

Instance Method Summary collapse

Instance Method Details

#on_if(node) ⇒ Object

unless desugars to if and the ternary ? : is an if node, so a single on_if covers both (plus modifier forms). until mirrors while — both expose condition.



48
49
50
# File 'lib/rubocop/cop/dev_doc/style/literal_operator_in_condition.rb', line 48

def on_if(node)
  check(node.condition)
end

#on_while(node) ⇒ Object Also known as: on_until



52
53
54
# File 'lib/rubocop/cop/dev_doc/style/literal_operator_in_condition.rb', line 52

def on_while(node)
  check(node.condition)
end