Skip to content

Commit

Permalink
Merge pull request #14 from ytjmt/disallow_ivar_in_class_methods_dsl
Browse files Browse the repository at this point in the history
Disallow instance variables in `ActiveSupport::Concern#class_methods`
  • Loading branch information
mikegee authored Jul 21, 2022
2 parents 505ac0c + 8687657 commit 2d4a0b0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/rubocop/cop/thread_safety/instance_variable_in_class_method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ module ThreadSafety
# end
#
# module Example
# class_methods do
# def test(params)
# @params = params
# end
# end
# end
#
# module Example
# module_function
#
# def test(params)
Expand Down Expand Up @@ -111,6 +119,19 @@ def in_def_sclass?(node)
end

def in_def_class_methods?(node)
in_def_class_methods_dsl?(node) || in_def_class_methods_module?(node)
end

def in_def_class_methods_dsl?(node)
node.ancestors.any? do |ancestor|
next unless ancestor.block_type?
next unless ancestor.children.first.is_a? AST::SendNode

ancestor.children.first.command? :class_methods
end
end

def in_def_class_methods_module?(node)
defn = node.ancestors.find(&:def_type?)
return unless defn

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,19 @@ def some_method(params)
RUBY
end

it 'registers an offense for assigning an ivar in class_methods' do
expect_offense(<<~RUBY)
module Test
class_methods do
def some_method(params)
@params = params
^^^^^^^ Avoid instance variables in class methods.
end
end
end
RUBY
end

it 'registers an offense for assigning an ivar in a class singleton method' do
expect_offense(<<~RUBY)
class Test
Expand Down Expand Up @@ -130,6 +143,19 @@ def some_method(params)
RUBY
end

it 'registers an offense for ivar_set in class_methods' do
expect_offense(<<~RUBY)
module Test
class_methods do
def some_method(params)
instance_variable_set(:@params, params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid instance variables in class methods.
end
end
end
RUBY
end

it 'registers an offense for ivar_set in define_singleton_method' do
expect_offense(<<~RUBY)
class Test
Expand Down

0 comments on commit 2d4a0b0

Please sign in to comment.