Class: RuboCop::Cop::MagicNumbers::NoAssignment

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/magic_numbers/no_assignment.rb

Overview

Adds violations for magic numbers, aka assignments to variables with bare numbers, configurable by literal type. Can detect local, instance, global, and setter assignment, and works on multiple assignment.

bad: hours = 24

good: HOURS_IN_ONE_DAY = 24

Constant Summary collapse

MAGIC_NUMBER_ARGUMENT_TO_SETTER_PATTERN =
<<-PATTERN
  (send
    ({send self} ...)
    $_
    (%<illegal_scalar_pattern>s _)
  )
PATTERN
MAGIC_NUMBER_MULTI_ASSIGN_PATTERN =
<<-PATTERN
  (masgn
    (mlhs ({lvasgn ivasgn send} ...)+)
    (array <(%<illegal_scalar_pattern>s _) ...>)
  )
PATTERN
LOCAL_VARIABLE_ASSIGN_MSG =
'Do not use magic number local variables'
INSTANCE_VARIABLE_ASSIGN_MSG =
'Do not use magic number instance variables'
MULTIPLE_ASSIGN_MSG =
'Do not use magic numbers in multiple assignments'
PROPERTY_MSG =
'Do not use magic numbers to set properties'
DEFAULT_CONFIG =
{
  'AllowedAssignments' => %w[class_variables global_variables]
}.freeze

Constants inherited from Base

Base::CONFIG_ALL, Base::CONFIG_FLOAT, Base::CONFIG_INTEGER, Base::CONFIG_NAME_FORBIDDEN_NUMERICS, Base::ILLEGAL_SCALAR_TYPES

Instance Method Summary collapse

Instance Method Details

#cop_configObject



38
39
40
# File 'lib/rubocop/cop/magic_numbers/no_assignment.rb', line 38

def cop_config
  DEFAULT_CONFIG.merge(super)
end

#on_instance_variable_assignment(node) ⇒ Object Also known as: on_ivasgn



50
51
52
53
54
55
# File 'lib/rubocop/cop/magic_numbers/no_assignment.rb', line 50

def on_instance_variable_assignment(node)
  return unless illegal_scalar_value?(node)
  return unless node_within_method?(node)

  add_offense(node, message: INSTANCE_VARIABLE_ASSIGN_MSG)
end

#on_local_variable_assignment(node) ⇒ Object Also known as: on_lvasgn



42
43
44
45
46
47
# File 'lib/rubocop/cop/magic_numbers/no_assignment.rb', line 42

def on_local_variable_assignment(node)
  return unless illegal_scalar_value?(node)
  return unless node_within_method?(node)

  add_offense(node, message: LOCAL_VARIABLE_ASSIGN_MSG)
end

#on_message_send(node) ⇒ Object Also known as: on_send



58
59
60
61
62
63
# File 'lib/rubocop/cop/magic_numbers/no_assignment.rb', line 58

def on_message_send(node)
  return unless illegal_scalar_argument_to_setter?(node)
  return unless node_within_method?(node)

  add_offense(node, message: PROPERTY_MSG)
end

#on_multiple_assign(node) ⇒ Object Also known as: on_masgn



66
67
68
69
70
71
72
73
# File 'lib/rubocop/cop/magic_numbers/no_assignment.rb', line 66

def on_multiple_assign(node)
  # multiassignment nodes aren't AsgnNode typed, so we need to have a
  # special approach to deconstruct them and assess if they contain magic
  # numbers amongst their assignments
  return false unless illegal_multi_assign_right_hand_side?(node)

  add_offense(node, message: MULTIPLE_ASSIGN_MSG)
end