Skip to content

Commit

Permalink
Merge pull request #43 from viralpraxis/make-class-attribute-detectio…
Browse files Browse the repository at this point in the history
…n-configurable

Make `class_attribute` detection configurable
  • Loading branch information
viralpraxis authored Sep 11, 2024
2 parents bdb42f5 + b66a910 commit 6bafd21
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 1 deletion.
1 change: 1 addition & 0 deletions config/default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
ThreadSafety/ClassAndModuleAttributes:
Description: 'Avoid mutating class and module attributes.'
Enabled: true
ActiveSupportClassAttributeAllowed: false

ThreadSafety/InstanceVariableInClassMethod:
Description: 'Avoid using instance variables in class methods.'
Expand Down
10 changes: 10 additions & 0 deletions docs/modules/ROOT/pages/cops_threadsafety.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ class User
end
----
=== Configurable attributes
|===
| Name | Default value | Configurable values
| ActiveSupportClassAttributeAllowed
| `false`
| Boolean
|===
== ThreadSafety/DirChdir
|===
Expand Down
13 changes: 12 additions & 1 deletion lib/rubocop/cop/thread_safety/class_and_module_attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,15 @@ class ClassAndModuleAttributes < Base
...)
MATCHER

# @!method class_attr?(node)
def_node_matcher :class_attr?, <<~MATCHER
(send nil?
:class_attribute
...)
MATCHER

def on_send(node)
return unless mattr?(node) || singleton_attr?(node)
return unless mattr?(node) || (!class_attribute_allowed? && class_attr?(node)) || singleton_attr?(node)

add_offense(node)
end
Expand All @@ -66,6 +73,10 @@ def defined_in_singleton_class?(node)

false
end

def class_attribute_allowed?
cop_config['ActiveSupportClassAttributeAllowed']
end
end
end
end
Expand Down
21 changes: 21 additions & 0 deletions spec/rubocop/cop/thread_safety/class_and_module_attributes_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,27 @@ class Test
RUBY
end

it 'registers an offense for `class_attribute`' do
expect_offense(<<~RUBY)
class Test
class_attribute :foobar
^^^^^^^^^^^^^^^^^^^^^^^ #{msg}
end
RUBY
end

context 'with `ActiveSupportClassAttributeAllowed` option set to `true`' do
let(:cop_config) { { 'ActiveSupportClassAttributeAllowed' => true } }

it 'does not register an offense for `class_attribute`' do
expect_no_offenses(<<~RUBY)
class Test
class_attribute :foobar
end
RUBY
end
end

it 'registers no offense for other class macro calls' do
expect_no_offenses(<<~RUBY)
class Test
Expand Down

0 comments on commit 6bafd21

Please sign in to comment.