class RuboCop::Cop::Style::RedundantSelfAssignment

Checks for places where redundant assignments are made for in place modification methods.

@safety

This cop is unsafe, because it can produce false positives for
user defined methods having one of the expected names, but not modifying
its receiver in place.

@example

# bad
args = args.concat(ary)
hash = hash.merge!(other)

# good
args.concat(foo)
args += foo
hash.merge!(other)

# bad
self.foo = foo.concat(ary)

# good
foo.concat(ary)
self.foo += ary

Constants

ASSIGNMENT_TYPE_TO_RECEIVER_TYPE
METHODS_RETURNING_SELF
MSG

Public Instance Methods

on_cvasgn(node)
Alias for: on_lvasgn
on_gvasgn(node)
Alias for: on_lvasgn
on_ivasgn(node)
Alias for: on_lvasgn
on_lvasgn(node) click to toggle source
# File lib/rubocop/cop/style/redundant_self_assignment.rb, line 52
def on_lvasgn(node)
  lhs, rhs = *node
  receiver, method_name, = *rhs
  return unless receiver && method_returning_self?(method_name)

  receiver_type = ASSIGNMENT_TYPE_TO_RECEIVER_TYPE[node.type]
  return unless receiver.type == receiver_type && receiver.children.first == lhs

  message = format(MSG, method_name: method_name)
  add_offense(node.loc.operator, message: message) do |corrector|
    corrector.replace(node, rhs.source)
  end
end
Also aliased as: on_ivasgn, on_cvasgn, on_gvasgn
on_send(node) click to toggle source
# File lib/rubocop/cop/style/redundant_self_assignment.rb, line 69
def on_send(node)
  return unless node.assignment_method?
  return unless redundant_assignment?(node)

  message = format(MSG, method_name: node.first_argument.method_name)
  add_offense(node.loc.operator, message: message) do |corrector|
    corrector.remove(correction_range(node))
  end
end

Private Instance Methods

correction_range(node) click to toggle source
# File lib/rubocop/cop/style/redundant_self_assignment.rb, line 112
def correction_range(node)
  range_between(node.source_range.begin_pos, node.first_argument.source_range.begin_pos)
end
method_returning_self?(method_name) click to toggle source
# File lib/rubocop/cop/style/redundant_self_assignment.rb, line 81
def method_returning_self?(method_name)
  METHODS_RETURNING_SELF.include?(method_name)
end
redundant_assignment?(node) click to toggle source
# File lib/rubocop/cop/style/redundant_self_assignment.rb, line 105
def redundant_assignment?(node)
  receiver_name = node.method_name.to_s[0...-1].to_sym

  redundant_self_assignment?(node, receiver_name) ||
    redundant_nonself_assignment?(node, node.receiver, receiver_name)
end