/
access_modifier_declarations.rb
135 lines (119 loc) · 3.23 KB
/
access_modifier_declarations.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# Access modifiers should be declared to apply to a group of methods
# or inline before each method, depending on configuration.
# EnforcedStyle config covers only method definitions.
# Applications of visibility methods to symbols can be controlled
# using AllowModifiersOnSymbols config.
#
# @example EnforcedStyle: group (default)
# # bad
# class Foo
#
# private def bar; end
# private def baz; end
#
# end
#
# # good
# class Foo
#
# private
#
# def bar; end
# def baz; end
#
# end
#
# @example EnforcedStyle: inline
# # bad
# class Foo
#
# private
#
# def bar; end
# def baz; end
#
# end
#
# # good
# class Foo
#
# private def bar; end
# private def baz; end
#
# end
#
# @example AllowModifiersOnSymbols: true
# # good
# class Foo
#
# private :bar, :baz
#
# end
#
# @example AllowModifiersOnSymbols: false
# # bad
# class Foo
#
# private :bar, :baz
#
# end
class AccessModifierDeclarations < Base
include ConfigurableEnforcedStyle
GROUP_STYLE_MESSAGE = [
'`%<access_modifier>s` should not be',
'inlined in method definitions.'
].join(' ')
INLINE_STYLE_MESSAGE = [
'`%<access_modifier>s` should be',
'inlined in method definitions.'
].join(' ')
RESTRICT_ON_SEND = %i[private protected public module_function].freeze
def_node_matcher :access_modifier_with_symbol?, <<~PATTERN
(send nil? {:private :protected :public} (sym _))
PATTERN
def on_send(node)
return unless node.access_modifier?
return if node.parent&.pair_type?
return if allow_modifiers_on_symbols?(node)
if offense?(node)
add_offense(node.loc.selector) if opposite_style_detected
else
correct_style_detected
end
end
private
def allow_modifiers_on_symbols?(node)
cop_config['AllowModifiersOnSymbols'] && access_modifier_with_symbol?(node)
end
def offense?(node)
(group_style? && access_modifier_is_inlined?(node)) ||
(inline_style? && access_modifier_is_not_inlined?(node))
end
def group_style?
style == :group
end
def inline_style?
style == :inline
end
def access_modifier_is_inlined?(node)
node.arguments.any?
end
def access_modifier_is_not_inlined?(node)
!access_modifier_is_inlined?(node)
end
def message(range)
access_modifier = range.source
if group_style?
format(GROUP_STYLE_MESSAGE, access_modifier: access_modifier)
elsif inline_style?
format(INLINE_STYLE_MESSAGE, access_modifier: access_modifier)
end
end
end
end
end
end