class Rubocop::Cop::Lint::AssignmentInCondition

This cop checks for assignments in the conditions of if/while/until.

Constants

ASGN_NODES
MSG

Public Instance Methods

on_if(node) click to toggle source
Calls superclass method
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 12
def on_if(node)
  check(node)
  super
end
on_until(node) click to toggle source
Calls superclass method
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 22
def on_until(node)
  check(node)
  super
end
on_while(node) click to toggle source
Calls superclass method
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 17
def on_while(node)
  check(node)
  super
end

Private Instance Methods

check(node) click to toggle source
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 29
def check(node)
  condition, = *node

  on_node([:begin, *ASGN_NODES], condition) do |asgn_node|
    # skip safe assignment nodes if safe assignment is allowed
    return if safe_assignment_allowed? && safe_assignment?(asgn_node)

    # assignment nodes from shorthand ops like ||= don't have operator
    if asgn_node.type != :begin && asgn_node.loc.operator
      add_offence(:warning, asgn_node.loc.operator, MSG)
    end
  end
end
safe_assignment?(node) click to toggle source
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 43
def safe_assignment?(node)
  node.type == :begin && node.children.size == 1 &&
    ASGN_NODES.include?(node.children[0].type)
end
safe_assignment_allowed?() click to toggle source
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 48
def safe_assignment_allowed?
  AssignmentInCondition.config['AllowSafeAssignment']
end