/
predicate_name.rb
108 lines (94 loc) · 2.69 KB
/
predicate_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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# frozen_string_literal: true
module RuboCop
module Cop
module Naming
# This cop makes sure that predicates are named properly.
#
# @example
# # bad
# def is_even(value)
# end
#
# def is_even?(value)
# end
#
# # good
# def even?(value)
# end
#
# # bad
# def has_value
# end
#
# def has_value?
# end
#
# # good
# def value?
# end
class PredicateName < Cop
def_node_matcher :dynamic_method_define, <<~PATTERN
(send nil? #method_definition_macros
(sym $_)
...)
PATTERN
def on_send(node)
dynamic_method_define(node) do |method_name|
predicate_prefixes.each do |prefix|
next if allowed_method_name?(method_name.to_s, prefix)
add_offense(
node,
location: node.first_argument.loc.expression,
message: message(method_name,
expected_name(method_name.to_s, prefix))
)
end
end
end
def on_def(node)
predicate_prefixes.each do |prefix|
method_name = node.method_name.to_s
next if allowed_method_name?(method_name, prefix)
add_offense(
node,
location: :name,
message: message(method_name, expected_name(method_name, prefix))
)
end
end
alias on_defs on_def
private
def allowed_method_name?(method_name, prefix)
!method_name.match(/^#{prefix}[^0-9]/) ||
method_name == expected_name(method_name, prefix) ||
method_name.end_with?('=') ||
allowed_methods.include?(method_name)
end
def expected_name(method_name, prefix)
new_name = if forbidden_prefixes.include?(prefix)
method_name.sub(prefix, '')
else
method_name.dup
end
new_name << '?' unless method_name.end_with?('?')
new_name
end
def message(method_name, new_name)
"Rename `#{method_name}` to `#{new_name}`."
end
def forbidden_prefixes
cop_config['ForbiddenPrefixes']
end
def predicate_prefixes
cop_config['NamePrefix']
end
def allowed_methods
cop_config['AllowedMethods']
end
def method_definition_macros(macro_name)
cop_config['MethodDefinitionMacros'].include?(macro_name.to_s)
end
end
end
end
end