class RuboCop::Cop::Style::SelfAssignment

This cop enforces the use the shorthand for self-assignment.

@example

# bad
x = x + 1

# good
x += 1

Constants

MSG
OPS

Public Instance Methods

on_cvasgn(node) click to toggle source
# File lib/rubocop/cop/style/self_assignment.rb, line 27
def on_cvasgn(node)
  check(node, :cvar)
end
on_ivasgn(node) click to toggle source
# File lib/rubocop/cop/style/self_assignment.rb, line 23
def on_ivasgn(node)
  check(node, :ivar)
end
on_lvasgn(node) click to toggle source
# File lib/rubocop/cop/style/self_assignment.rb, line 19
def on_lvasgn(node)
  check(node, :lvar)
end

Private Instance Methods

apply_autocorrect(node, rhs, operator, new_rhs) click to toggle source
# File lib/rubocop/cop/style/self_assignment.rb, line 84
def apply_autocorrect(node, rhs, operator, new_rhs)
  lambda do |corrector|
    corrector.insert_before(node.loc.operator, operator)
    corrector.replace(rhs.source_range, new_rhs.source)
  end
end
autocorrect(node) click to toggle source
# File lib/rubocop/cop/style/self_assignment.rb, line 64
def autocorrect(node)
  _var_name, rhs = *node

  if rhs.type == :send
    autocorrect_send_node(node, rhs)
  elsif [:and, :or].include?(rhs.type)
    autocorrect_boolean_node(node, rhs)
  end
end
autocorrect_boolean_node(node, rhs) click to toggle source
# File lib/rubocop/cop/style/self_assignment.rb, line 79
def autocorrect_boolean_node(node, rhs)
  _first_operand, second_operand = *rhs
  apply_autocorrect(node, rhs, rhs.loc.operator.source, second_operand)
end
autocorrect_send_node(node, rhs) click to toggle source
# File lib/rubocop/cop/style/self_assignment.rb, line 74
def autocorrect_send_node(node, rhs)
  _receiver, method_name, args = *rhs
  apply_autocorrect(node, rhs, method_name.to_s, args)
end
check(node, var_type) click to toggle source
# File lib/rubocop/cop/style/self_assignment.rb, line 33
def check(node, var_type)
  var_name, rhs = *node
  return unless rhs

  if rhs.type == :send
    check_send_node(node, rhs, var_name, var_type)
  elsif [:and, :or].include?(rhs.type)
    check_boolean_node(node, rhs, var_name, var_type)
  end
end
check_boolean_node(node, rhs, var_name, var_type) click to toggle source
# File lib/rubocop/cop/style/self_assignment.rb, line 54
def check_boolean_node(node, rhs, var_name, var_type)
  first_operand, _second_operand = *rhs

  target_node = s(var_type, var_name)
  return unless first_operand == target_node

  operator = rhs.loc.operator.source
  add_offense(node, :expression, format(MSG, operator))
end
check_send_node(node, rhs, var_name, var_type) click to toggle source
# File lib/rubocop/cop/style/self_assignment.rb, line 44
def check_send_node(node, rhs, var_name, var_type)
  receiver, method_name, *_args = *rhs
  return unless OPS.include?(method_name)

  target_node = s(var_type, var_name)
  return unless receiver == target_node

  add_offense(node, :expression, format(MSG, method_name))
end