class RuboCop::Cop::Lint::DisjunctiveAssignmentInConstructor
end
@x = 1
def initialize
# good
end
@x ||= 1
def initialize
# bad
@example
the value for ‘@config`.
Without the disjunctive assignment, `Derived` will be unable to override
—-
end
end
super
@config = ’derived’
def initialize
class Derived < Base
end
end
@config ||= ‘base’
def initialize
class Base
—-
[source,ruby]
method is redefined in a subclass that calls super. For example:
This cop is unsafe because it can register a false positive when a
@safety
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.
Checks constructors for disjunctive assignments (‘||=`) that should
def check(node)
-
node
(DefNode
) -- a constructor definition
def check(node) return unless node.method?(: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)
-
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)
-
node
(Node
) -- a disjunctive assignment
def check_disjunctive_assignment(node) lhs = node.child_nodes.first return unless lhs.ivasgn_type? add_offense(node.loc.operator) do |corrector| corrector.replace(node.loc.operator, '=') end end
def on_def(node)
def on_def(node) check(node) end