/
constant_resolution.rb
89 lines (81 loc) · 2.16 KB
/
constant_resolution.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
85
86
87
88
89
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# Check that certain constants are fully qualified.
#
# This is not enabled by default because it would mark a lot of offenses
# unnecessarily.
#
# Generally, gems should fully qualify all constants to avoid conflicts with
# the code that uses the gem. Enable this cop without using `Only`/`Ignore`
#
# Large projects will over time end up with one or two constant names that
# are problematic because of a conflict with a library or just internally
# using the same name a namespace and a class. To avoid too many unnecessary
# offenses, Enable this cop with `Only: [The, Constant, Names, Causing, Issues]`
#
# @example
# # By default checks every constant
#
# # bad
# User
#
# # bad
# User::Login
#
# # good
# ::User
#
# # good
# ::User::Login
#
# @example Only: ['Login']
# # Restrict this cop to only being concerned about certain constants
#
# # bad
# Login
#
# # good
# ::Login
#
# # good
# User::Login
#
# @example Ignore: ['Login']
# # Restrict this cop not being concerned about certain constants
#
# # bad
# User
#
# # good
# ::User::Login
#
# # good
# Login
#
class ConstantResolution < Cop
MSG = 'Fully qualify this constant to avoid possibly ambiguous resolution.'
def_node_matcher :unqualified_const?, <<~PATTERN
(const nil? #const_name?)
PATTERN
def on_const(node)
return unless unqualified_const?(node)
add_offense(node)
end
private
def const_name?(name)
name = name.to_s
(allowed_names.empty? || allowed_names.include?(name)) &&
!ignored_names.include?(name)
end
def allowed_names
cop_config['Only']
end
def ignored_names
cop_config['Ignore']
end
end
end
end
end