-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
class_structure.rb
305 lines (276 loc) · 9.31 KB
/
class_structure.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks if the code style follows the ExpectedOrder configuration:
#
# `Categories` allows us to map macro names into a category.
#
# Consider an example of code style that covers the following order:
#
# * Module inclusion (include, prepend, extend)
# * Constants
# * Associations (has_one, has_many)
# * Public attribute macros (attr_accessor, attr_writer, attr_reader)
# * Other macros (validates, validate)
# * Public class methods
# * Initializer
# * Public instance methods
# * Protected attribute macros (attr_accessor, attr_writer, attr_reader)
# * Protected instance methods
# * Private attribute macros (attr_accessor, attr_writer, attr_reader)
# * Private instance methods
#
# You can configure the following order:
#
# [source,yaml]
# ----
# Layout/ClassStructure:
# ExpectedOrder:
# - module_inclusion
# - constants
# - association
# - public_attribute_macros
# - public_delegate
# - macros
# - public_class_methods
# - initializer
# - public_methods
# - protected_attribute_macros
# - protected_methods
# - private_attribute_macros
# - private_delegate
# - private_methods
# ----
#
# Instead of putting all literals in the expected order, is also
# possible to group categories of macros. Visibility levels are handled
# automatically.
#
# [source,yaml]
# ----
# Layout/ClassStructure:
# Categories:
# association:
# - has_many
# - has_one
# attribute_macros:
# - attr_accessor
# - attr_reader
# - attr_writer
# macros:
# - validates
# - validate
# module_inclusion:
# - include
# - prepend
# - extend
# ----
#
# @example
# # bad
# # Expect extend be before constant
# class Person < ApplicationRecord
# has_many :orders
# ANSWER = 42
#
# extend SomeModule
# include AnotherModule
# end
#
# # good
# class Person
# # extend and include go first
# extend SomeModule
# include AnotherModule
#
# # inner classes
# CustomError = Class.new(StandardError)
#
# # constants are next
# SOME_CONSTANT = 20
#
# # afterwards we have public attribute macros
# attr_reader :name
#
# # followed by other macros (if any)
# validates :name
#
# # then we have public delegate macros
# delegate :to_s, to: :name
#
# # public class methods are next in line
# def self.some_method
# end
#
# # initialization goes between class methods and instance methods
# def initialize
# end
#
# # followed by other public instance methods
# def some_method
# end
#
# # protected attribute macros and methods go next
# protected
#
# attr_reader :protected_name
#
# def some_protected_method
# end
#
# # private attribute macros, delegate macros and methods
# # are grouped near the end
# private
#
# attr_reader :private_name
#
# delegate :some_private_delegate, to: :name
#
# def some_private_method
# end
# end
#
# @see https://rubystyle.guide#consistent-classes
class ClassStructure < Base
include VisibilityHelp
extend AutoCorrector
HUMANIZED_NODE_TYPE = {
casgn: :constants,
defs: :class_methods,
def: :public_methods,
sclass: :class_singleton
}.freeze
MSG = '`%<category>s` is supposed to appear before ' \
'`%<previous>s`.'
# Validates code style on class declaration.
# Add offense when find a node out of expected order.
def on_class(class_node)
previous = -1
walk_over_nested_class_definition(class_node) do |node, category|
index = expected_order.index(category)
if index < previous
message = format(MSG, category: category,
previous: expected_order[previous])
add_offense(node, message: message) do |corrector|
autocorrect(corrector, node)
end
end
previous = index
end
end
private
# Autocorrect by swapping between two nodes autocorrecting them
def autocorrect(corrector, node)
node_classification = classify(node)
previous = left_siblings_of(node).find do |sibling|
classification = classify(sibling)
!ignore?(classification) && node_classification != classification
end
current_range = source_range_with_comment(node)
previous_range = source_range_with_comment(previous)
corrector.insert_before(previous_range, current_range.source)
corrector.remove(current_range)
end
# Classifies a node to match with something in the {expected_order}
# @param node to be analysed
# @return String when the node type is a `:block` then
# {classify} recursively with the first children
# @return String when the node type is a `:send` then {find_category}
# by method name
# @return String otherwise trying to {humanize_node} of the current node
def classify(node)
return node.to_s unless node.respond_to?(:type)
case node.type
when :block
classify(node.send_node)
when :send
find_category(node)
else
humanize_node(node)
end.to_s
end
# Categorize a node according to the {expected_order}
# Try to match {categories} values against the node's method_name given
# also its visibility.
# @param node to be analysed.
# @return [String] with the key category or the `method_name` as string
def find_category(node)
name = node.method_name.to_s
category, = categories.find { |_, names| names.include?(name) }
key = category || name
visibility_key = "#{node_visibility(node)}_#{key}"
expected_order.include?(visibility_key) ? visibility_key : key
end
def walk_over_nested_class_definition(class_node)
class_elements(class_node).each do |node|
classification = classify(node)
next if ignore?(classification)
yield node, classification
end
end
def class_elements(class_node)
class_def = class_node.body
return [] unless class_def
if class_def.def_type? || class_def.send_type?
[class_def]
else
class_def.children.compact
end
end
def ignore?(classification)
classification.nil? ||
classification.to_s.end_with?('=') ||
expected_order.index(classification).nil?
end
def humanize_node(node)
if node.def_type?
return :initializer if node.method?(:initialize)
return "#{node_visibility(node)}_methods"
end
HUMANIZED_NODE_TYPE[node.type] || node.type
end
def source_range_with_comment(node)
begin_pos, end_pos =
if node.def_type?
start_node = find_visibility_start(node) || node
end_node = find_visibility_end(node) || node
[begin_pos_with_comment(start_node),
end_position_for(end_node) + 1]
else
[begin_pos_with_comment(node), end_position_for(node)]
end
Parser::Source::Range.new(buffer, begin_pos, end_pos)
end
def end_position_for(node)
end_line = buffer.line_for_position(node.loc.expression.end_pos)
buffer.line_range(end_line).end_pos
end
def begin_pos_with_comment(node)
first_comment = nil
(node.first_line - 1).downto(1) do |annotation_line|
break unless (comment = processed_source.comment_at_line(annotation_line))
first_comment = comment
end
start_line_position(first_comment || node)
end
def start_line_position(node)
buffer.line_range(node.loc.line).begin_pos - 1
end
def buffer
processed_source.buffer
end
# Load expected order from `ExpectedOrder` config.
# Define new terms in the expected order by adding new {categories}.
def expected_order
cop_config['ExpectedOrder']
end
# Setting categories hash allow you to group methods in group to match
# in the {expected_order}.
def categories
cop_config['Categories']
end
end
end
end
end