Class: RuboCop::Cop::Style::ClassVars

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/style/class_vars.rb

Overview

Checks for uses of class variables. Offenses are signaled only on assignment to class variables to reduce the number of offenses that would be reported.

You have to be careful when setting a value for a class variable; if a class has been inherited, changing the value of a class variable also affects the inheriting classes. This means that it’s almost always better to use a class instance variable instead.

Examples:

# bad class A @@test = 10 end class A def self.test(name, value) class_variable_set("@@#{name}", value) end end class A; end A.class_variable_set(:@@test, 10) # good class A @test = 10 end class A def test @@test # you can access class variable without offense  end end class A def self.test(name) class_variable_get("@@#{name}") # you can access without offense  end end

Constant Summary collapse

MSG =
'Replace class var %<class_var>s with a class instance var.'
RESTRICT_ON_SEND =
%i[class_variable_set].freeze

Instance Attribute Summary

Attributes inherited from Base

#config, #processed_source

Instance Method Summary collapse

Methods inherited from Base

#active_support_extensions_enabled?, #add_global_offense, #add_offense, #always_autocorrect?, autocorrect_incompatible_with, badge, #begin_investigation, #callbacks_needed, callbacks_needed, #config_to_allow_offenses, #config_to_allow_offenses=, #contextual_autocorrect?, #cop_config, #cop_name, cop_name, department, documentation_url, exclude_from_registry, #excluded_file?, #external_dependency_checksum, inherited, #initialize, #inspect, joining_forces, lint?, match?, #message, #offenses, #on_investigation_end, #on_new_investigation, #on_other_file, #parse, #parser_engine, #ready, #relevant_file?, requires_gem, #string_literals_frozen_by_default?, support_autocorrect?, support_multiple_source?, #target_gem_version, #target_rails_version, #target_ruby_version

Methods included from ExcludeLimit

#exclude_limit

Methods included from AutocorrectLogic

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #autocorrect_with_disable_uncorrectable?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

silence_warnings

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Method Details

#on_cvasgn(node) ⇒ Object

 52 53 54
# File 'lib/rubocop/cop/style/class_vars.rb', line 52 def on_cvasgn(node) add_offense(node.loc.name, message: format(MSG, class_var: node.children.first)) end

#on_send(node) ⇒ Object

 56 57 58 59 60
# File 'lib/rubocop/cop/style/class_vars.rb', line 56 def on_send(node) return unless (first_argument = node.first_argument) add_offense(first_argument, message: format(MSG, class_var: first_argument.source)) end