Sha256: 1094168c5c245c5fe4d90288c60e0536555b9ae7d89924e761e3a84939c992b1
Contents?: true
Size: 1.69 KB
Versions: 3
Compression:
Stored size: 1.69 KB
Contents
# encoding: utf-8 module Rubocop module Cop module Style # This cop enforces the use the shorthand for self-assignment. # # @example # # # bad # x = x + 1 # # # good # x += 1 class SelfAssignment < Cop include AST::Sexp OPS = [:+, :-, :*, :**, :/, :|, :&] def on_lvasgn(node) check(node, :lvar) end def on_ivasgn(node) check(node, :ivar) end def on_cvasgn(node) check(node, :cvar) end 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 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) if receiver == target_node add_offense(node, :expression, "Use self-assignment shorthand `#{method_name}=`.") end end def check_boolean_node(node, rhs, var_name, var_type) first_operand, _second_operand = *rhs target_node = s(var_type, var_name) if first_operand == target_node operator = rhs.loc.operator.source add_offense(node, :expression, "Use self-assignment shorthand `#{operator}=`.") end end end end end end
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
rubocop-0.21.0 | lib/rubocop/cop/style/self_assignment.rb |
rubocop-0.20.1 | lib/rubocop/cop/style/self_assignment.rb |
rubocop-0.20.0 | lib/rubocop/cop/style/self_assignment.rb |