Class: RuboCop::Cop::ThreadSafety::ClassInstanceVariable

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/thread_safety/class_instance_variable.rb

Overview

Avoid class instance variables.

Examples:

# bad
class User
  def self.notify(info)
    @info = validate(info)
    Notifier.new(@info).deliver
  end
end

class Model
  class << self
    def table_name(name)
      @table_name = name
    end
  end
end

class Host
  %i[uri port].each do |key|
    define_singleton_method("#{key}=") do |value|
      instance_variable_set("@#{key}", value)
    end
  end
end

module Example
  module ClassMethods
    def test(params)
      @params = params
    end
  end
end

module Example
  class_methods do
    def test(params)
      @params = params
    end
  end
end

module Example
  module_function

  def test(params)
    @params = params
  end
end

module Example
  def test(params)
    @params = params
  end

  module_function :test
end

Constant Summary collapse

MSG =
'Avoid class instance variables.'
RESTRICT_ON_SEND =
%i[
  instance_variable_set
  instance_variable_get
].freeze

Instance Method Summary collapse

Instance Method Details

#instance_variable_get_call?(node) ⇒ Object



77
78
79
# File 'lib/rubocop/cop/thread_safety/class_instance_variable.rb', line 77

def_node_matcher :instance_variable_get_call?, <<~MATCHER
  (send nil? :instance_variable_get (...))
MATCHER

#instance_variable_set_call?(node) ⇒ Object



72
73
74
# File 'lib/rubocop/cop/thread_safety/class_instance_variable.rb', line 72

def_node_matcher :instance_variable_set_call?, <<~MATCHER
  (send nil? :instance_variable_set (...) (...))
MATCHER

#on_ivar(node) ⇒ Object Also known as: on_ivasgn



81
82
83
84
85
86
87
# File 'lib/rubocop/cop/thread_safety/class_instance_variable.rb', line 81

def on_ivar(node)
  return unless class_method_definition?(node)
  return if method_definition?(node)
  return if synchronized?(node)

  add_offense(node.loc.name)
end

#on_send(node) ⇒ Object



90
91
92
93
94
95
96
97
# File 'lib/rubocop/cop/thread_safety/class_instance_variable.rb', line 90

def on_send(node)
  return unless instance_variable_call?(node)
  return unless class_method_definition?(node)
  return if method_definition?(node)
  return if synchronized?(node)

  add_offense(node)
end