forked from covermymeds/rubocop-thread_safety
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
class_and_module_attributes.rb
76 lines (65 loc) · 1.94 KB
/
class_and_module_attributes.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
# frozen_string_literal: true
module RuboCop
module Cop
module ThreadSafety
# Avoid mutating class and module attributes.
#
# They are implemented by class variables, which are not thread-safe.
#
# @example
# # bad
# class User
# cattr_accessor :current_user
# end
class ClassAndModuleAttributes < Base
MSG = 'Avoid mutating class and module attributes.'
RESTRICT_ON_SEND = %i[
mattr_writer mattr_accessor cattr_writer cattr_accessor
class_attribute
attr attr_accessor attr_writer
attr_internal attr_internal_accessor attr_internal_writer
].freeze
def_node_matcher :mattr?, <<~MATCHER
(send nil?
{:mattr_writer :mattr_accessor :cattr_writer :cattr_accessor}
...)
MATCHER
def_node_matcher :attr?, <<~MATCHER
(send nil?
{:attr :attr_accessor :attr_writer}
...)
MATCHER
def_node_matcher :attr_internal?, <<~MATCHER
(send nil?
{:attr_internal :attr_internal_accessor :attr_internal_writer}
...)
MATCHER
def_node_matcher :class_attr?, <<~MATCHER
(send nil?
:class_attribute
...)
MATCHER
def on_send(node)
return unless mattr?(node) || class_attr?(node) ||
singleton_attr?(node)
add_offense(node, message: MSG)
end
private
def singleton_attr?(node)
(attr?(node) || attr_internal?(node)) &&
defined_in_singleton_class?(node)
end
def defined_in_singleton_class?(node)
node.ancestors.each do |ancestor|
case ancestor.type
when :def then return false
when :sclass then return true
else next
end
end
false
end
end
end
end
end