-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
mixin_grouping.rb
101 lines (83 loc) · 2.32 KB
/
mixin_grouping.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
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for grouping of mixins in `class` and `module` bodies.
# By default it enforces mixins to be placed in separate declarations,
# but it can be configured to enforce grouping them in one declaration.
#
# @example
#
# EnforcedStyle: separated (default)
#
# @bad
# class Foo
# include Bar, Qox
# end
#
# @good
# class Foo
# include Bar
# include Qox
# end
#
# EnforcedStyle: grouped
#
# @bad
# class Foo
# extend Bar
# extend Qox
# end
#
# @good
# class Foo
# extend Bar, Qox
# end
class MixinGrouping < Cop
include ConfigurableEnforcedStyle
MIXIN_METHODS = [:extend, :include, :prepend].freeze
MSG = 'Put `%s` mixins in %s.'.freeze
def on_send(node)
_reciever, method_name, *_args = *node
return unless MIXIN_METHODS.include?(method_name)
check(node)
end
private
def check(send_node)
if separated_style?
check_separated_style(send_node)
else
check_grouped_style(send_node)
end
end
def check_grouped_style(send_node)
return unless sibling_mixins?(send_node)
add_offense(send_node, :expression)
end
def check_separated_style(send_node)
_reciever, _method_name, *args = *send_node
return if args.one?
add_offense(send_node, :expression)
end
def sibling_mixins?(send_node)
siblings = send_node.parent.each_child_node(:send)
.reject { |sibling| sibling == send_node }
siblings.any? do |sibling_node|
sibling_node.method_name == send_node.method_name
end
end
def message(send_node)
suffix =
separated_style? ? 'separate statements' : 'a single statement'
format(MSG, send_node.method_name, suffix)
end
def grouped_style?
style == :grouped
end
def separated_style?
style == :separated
end
end
end
end
end