class RuboCop::Cop::Lint::DisjunctiveAssignmentInConstructor

end
@x = 1
def initialize
# good
end
@x ||= 1
def initialize
# bad
@example
disjunction is unnecessary. A plain assignment has the same effect.
In ruby, an instance variable is nil until a value is assigned, so the
instance variables.
So far, this cop is only concerned with disjunctive assignment of
be plain assignments.
This cop checks constructors for disjunctive assignments that should

def check(node)

Parameters:
  • node (DefNode) -- a constructor definition
def check(node)
  return unless node.method_name == :initialize
  check_body(node.body)
end

def check_body(body)

def check_body(body)
  return if body.nil?
  case body.type
  when :begin
    check_body_lines(body.child_nodes)
  else
    check_body_lines([body])
  end
end

def check_body_lines(lines)

Parameters:
  • lines (Array) -- the logical lines of the constructor
def check_body_lines(lines)
  lines.each do |line|
    case line.type
    when :or_asgn
      check_disjunctive_assignment(line)
    else
      # Once we encounter something other than a disjunctive
      # assignment, we cease our investigation, because we can't be
      # certain that any future disjunctive assignments are offensive.
      # You're off the case, detective!
      break
    end
  end
end

def check_disjunctive_assignment(node)

Parameters:
  • node (Node) -- a disjunctive assignment
def check_disjunctive_assignment(node)
  lhs = node.child_nodes.first
  add_offense(node, location: :operator) if lhs.ivasgn_type?
end

def on_def(node)

def on_def(node)
  check(node)
end