class RuboCop::Cop::Style::UnneededCondition

This cop checks for unnecessary conditional expressions.

@example

# bad
a = b ? b : c

# good
a = b || c

@example

# bad
if b
  b
else
  c
end

# good
b || c

# good
if b
  b
elsif cond
  c
end

Constants

MSG
UNNEEDED_CONDITION

Public Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/style/unneeded_condition.rb, line 46
def autocorrect(node)
  lambda do |corrector|
    if node.ternary?
      corrector.replace(range_of_offense(node), '||')
    elsif node.modifier_form? || !node.else_branch
      corrector.replace(node.source_range, node.if_branch.source)
    else
      corrected = make_ternary_form(node)

      corrector.replace(node.source_range, corrected)
    end
  end
end
on_if(node) click to toggle source
# File lib/rubocop/cop/style/unneeded_condition.rb, line 39
def on_if(node)
  return if node.elsif_conditional?
  return unless offense?(node)

  add_offense(node, location: range_of_offense(node))
end

Private Instance Methods

else_source(else_branch) click to toggle source
# File lib/rubocop/cop/style/unneeded_condition.rb, line 92
def else_source(else_branch)
  wrap_else =
    else_branch.basic_conditional? && else_branch.modifier_form?
  wrap_else ? "(#{else_branch.source})" : else_branch.source
end
make_ternary_form(node) click to toggle source
# File lib/rubocop/cop/style/unneeded_condition.rb, line 98
def make_ternary_form(node)
  _condition, if_branch, else_branch = *node
  ternary_form = [if_branch.source,
                  else_source(else_branch)].join(' || ')

  if node.parent&.send_type?
    "(#{ternary_form})"
  else
    ternary_form
  end
end
message(node) click to toggle source
# File lib/rubocop/cop/style/unneeded_condition.rb, line 62
def message(node)
  if node.modifier_form? || !node.else_branch
    UNNEEDED_CONDITION
  else
    MSG
  end
end
offense?(node) click to toggle source
# File lib/rubocop/cop/style/unneeded_condition.rb, line 76
def offense?(node)
  condition, if_branch, else_branch = *node

  return false if use_if_branch?(else_branch)

  condition == if_branch && !node.elsif? && (
    node.ternary? ||
    !else_branch.instance_of?(AST::Node) ||
    else_branch.single_line?
  )
end
range_of_offense(node) click to toggle source
# File lib/rubocop/cop/style/unneeded_condition.rb, line 70
def range_of_offense(node)
  return :expression unless node.ternary?

  range_between(node.loc.question.begin_pos, node.loc.colon.end_pos)
end
use_if_branch?(else_branch) click to toggle source
# File lib/rubocop/cop/style/unneeded_condition.rb, line 88
def use_if_branch?(else_branch)
  else_branch&.if_type?
end