class RuboCop::Cop::Lint::LiteralAssignmentInCondition
end
do_something
if x = y
# good
end
do_something
if x == 42
# good
end
do_something
if x = 42
# bad
@example
therefore this cop does not provide autocorrection.
As a lint cop, it cannot be determined if ‘==` is appropriate as intended,
—-
-e:1: warning: found `= literal’ in conditional, should be ==
$ ruby -we ‘if x = true; end’
—-
[source,console]
It emulates the following Ruby warning:
Checks for literal assignments in the conditions of ‘if`, `while`, and `until`.
def all_literals?(node)
def all_literals?(node) case node.type when :dstr, :xstr false when :array node.values.all? { |value| all_literals?(value) } when :hash (node.values + node.keys).all? { |item| all_literals?(item) } else node.respond_to?(:literal?) && node.literal? end end
def offense_range(asgn_node, rhs)
def offense_range(asgn_node, rhs) asgn_node.loc.operator.join(rhs.source_range.end) end
def on_if(node)
def on_if(node) traverse_node(node.condition) do |asgn_node| next unless asgn_node.loc.operator rhs = asgn_node.rhs next if !all_literals?(rhs) || parallel_assignment_with_splat_operator?(rhs) range = offense_range(asgn_node, rhs) add_offense(range, message: format(MSG, literal: rhs.source)) end end
def parallel_assignment_with_splat_operator?(node)
def parallel_assignment_with_splat_operator?(node) node.array_type? && node.values.first&.splat_type? end
def traverse_node(node, &block)
def traverse_node(node, &block) yield node if node.equals_asgn? node.each_child_node { |child| traverse_node(child, &block) } end