Class: RuboCop::Cop::MagicNumbers::NoAssignment
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::MagicNumbers::NoAssignment
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} ...)+)
{
$(%<illegal_scalar_pattern>s _)
$(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],
'PermittedValues' => []
}.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_config ⇒ Object
42
43
44
|
# File 'lib/rubocop/cop/magic_numbers/no_assignment.rb', line 42
def cop_config
DEFAULT_CONFIG.merge(super)
end
|
#on_instance_variable_assignment(node) ⇒ Object
Also known as:
on_ivasgn
54
55
56
57
58
59
|
# File 'lib/rubocop/cop/magic_numbers/no_assignment.rb', line 54
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
46
47
48
49
50
51
|
# File 'lib/rubocop/cop/magic_numbers/no_assignment.rb', line 46
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
62
63
64
65
66
67
|
# File 'lib/rubocop/cop/magic_numbers/no_assignment.rb', line 62
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
70
71
72
73
74
75
76
77
|
# File 'lib/rubocop/cop/magic_numbers/no_assignment.rb', line 70
def on_multiple_assign(node)
return false unless illegal_multi_assign_right_hand_side?(node)
add_offense(node, message: MULTIPLE_ASSIGN_MSG)
end
|