forked from rubocop/rubocop
/
constant_name.rb
84 lines (73 loc) · 2.53 KB
/
constant_name.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks whether constant names are written using
# SCREAMING_SNAKE_CASE.
#
# To avoid false positives, it ignores cases in which we cannot know
# for certain the type of value that would be assigned to a constant.
#
# @example
# # bad
# InchInCm = 2.54
# INCHinCM = 2.54
# Inch_In_Cm = 2.54
#
# # good
# INCH_IN_CM = 2.54
class ConstantName < Base
MSG = 'Use SCREAMING_SNAKE_CASE for constants.'
# Use POSIX character classes, so we allow accented characters rather
# than just standard ASCII characters
SNAKE_CASE = /^[[:digit:][:upper:]_]+$/.freeze
# @!method class_or_struct_return_method?(node)
def_node_matcher :class_or_struct_return_method?, <<~PATTERN
(send
(const _ {:Class :Struct}) :new
...)
PATTERN
def on_casgn(node)
if node.parent&.or_asgn_type?
lhs, value = *node.parent
_scope, const_name = *lhs
else
_scope, const_name, value = *node
end
# We cannot know the result of method calls like
# NewClass = something_that_returns_a_class
# It's also ok to assign a class constant another class constant,
# `Class.new(...)` or `Struct.new(...)`
# SomeClass = SomeOtherClass
# SomeClass = Class.new(...)
# SomeClass = Struct.new(...)
return if allowed_assignment?(value)
return if SNAKE_CASE.match?(const_name)
add_offense(node.loc.name)
end
private
def allowed_assignment?(value)
(value && %i[block const casgn].include?(value.type)) ||
allowed_method_call_on_rhs?(value) ||
class_or_struct_return_method?(value) ||
allowed_conditional_expression_on_rhs?(value)
end
def allowed_method_call_on_rhs?(node)
node&.send_type? &&
(node.receiver.nil? || !literal_receiver?(node))
end
# @!method literal_receiver?(node)
def_node_matcher :literal_receiver?, <<~PATTERN
{(send literal? ...)
(send (begin literal?) ...)}
PATTERN
def allowed_conditional_expression_on_rhs?(node)
node&.if_type? && contains_constant?(node)
end
def contains_constant?(node)
node.branches.compact.any?(&:const_type?)
end
end
end
end
end