class RuboCop::Cop::Style::RedundantSelfAssignmentBranch


foo = bar unless condition
# good
foo = condition ? foo : bar
# bad
foo = bar if condition
# good
foo = condition ? bar : foo
# bad
@example
class variable, and global variable that have state across methods with ‘nil`.
It only detects local variable because it may replace state of instance variable,
This cop checks for places where conditional branch makes redundant self-assignment.

def inconvertible_to_modifier?(if_branch, else_branch)

def inconvertible_to_modifier?(if_branch, else_branch)
  multiple_statements?(if_branch) || multiple_statements?(else_branch) ||
    (else_branch.respond_to?(:elsif?) && else_branch.elsif?)
end

def multiple_statements?(branch)

def multiple_statements?(branch)
  branch && branch.children.compact.count > 1
end

def on_lvasgn(node)

def on_lvasgn(node)
  variable, expression = *node
  return unless use_if_and_else_branch?(expression)
  if_branch = expression.if_branch
  else_branch = expression.else_branch
  return if inconvertible_to_modifier?(if_branch, else_branch)
  if self_assign?(variable, if_branch)
    register_offense(expression, if_branch, else_branch, 'unless')
  elsif self_assign?(variable, else_branch)
    register_offense(expression, else_branch, if_branch, 'if')
  end
end

def register_offense(if_node, offense_branch, opposite_branch, keyword)

def register_offense(if_node, offense_branch, opposite_branch, keyword)
  add_offense(offense_branch) do |corrector|
    assignment_value = opposite_branch ? opposite_branch.source : 'nil'
    replacement = "#{assignment_value} #{keyword} #{if_node.condition.source}"
    corrector.replace(if_node, replacement)
  end
end

def self_assign?(variable, branch)

def self_assign?(variable, branch)
  variable.to_s == branch&.source
end

def use_if_and_else_branch?(expression)

def use_if_and_else_branch?(expression)
  return false unless expression&.if_type?
  !expression.ternary? || !expression.else?
end