Class: RuboCop::Cop::Lint::ConstantReassignment

Inherits:
Base
  • Object
show all
Includes:
ProjectIndexHelp
Defined in:
lib/rubocop/cop/lint/constant_reassignment.rb

Overview

Checks for constant reassignments.

Emulates Ruby’s runtime warning “already initialized constant X” when a constant is reassigned in the same file and namespace.

The cop tracks constants defined via ‘NAME = value` syntax as well as class/module keyword definitions. It detects reassignment when a constant is first defined one way and then redefined using the `NAME = value` syntax.

The cop cannot catch all offenses, like, for example, when using metaprogramming (‘Module#const_set`).

By default the cop also cannot detect reassignment across files. When ‘AllCops/UseProjectIndex` is enabled and the `rubydex` gem is installed, the cop additionally consults the project-wide index and reports reassignments whose previous definition lives in another file.

The cop only takes into account constants assigned in a “simple” way: directly inside class/module definition, or within another constant. Other type of assignments (e.g., inside a conditional) are disregarded.

The cop also tracks constant removal using ‘Module#remove_const` with symbol or string argument.

Examples:

# bad
X = :foo
X = :bar

# bad
class A
  X = :foo
  X = :bar
end

# bad
module A
  X = :foo
  X = :bar
end

# bad
class FooError < StandardError; end
FooError = Class.new(RuntimeError)

# bad
module M; end
M = 1

# good - keep only one assignment
X = :bar

class A
  X = :bar
end

module A
  X = :bar
end

# good - use OR assignment
X = :foo
X ||= :bar

# good - use conditional assignment
X = :foo
X = :bar unless defined?(X)

# good - remove the assigned constant first
class A
  X = :foo
  remove_const :X
  X = :bar
end

Constant Summary collapse

MSG =
'Constant `%<constant>s` is already assigned in this namespace.'
CROSS_FILE_MSG =
'Constant `%<constant>s` is already assigned in `%<path>s`.'
RESTRICT_ON_SEND =
%i[remove_const].freeze

Constants included from ProjectIndexHelp

ProjectIndexHelp::BUILTIN_DOCUMENT_URI, ProjectIndexHelp::FILE_URI_PREFIX, ProjectIndexHelp::WINDOWS_DRIVE_PREFIX

Instance Attribute Summary

Attributes inherited from Base

#config, #processed_source, #project_index

Instance Method Summary collapse

Methods included from ProjectIndexHelp

#external_dependency_checksum

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

cop_dir_for, #exclude_limit, read_limits

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_casgn(node) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/rubocop/cop/lint/constant_reassignment.rb', line 107

def on_casgn(node)
  return unless fixed_constant_path?(node)
  return unless simple_assignment?(node)

  name = fully_qualified_constant_name(node)

  if constant_definitions.key?(name)
    add_offense(node, message: format(MSG, constant: constant_display_name(node)))
    return
  end

  constant_definitions[name] = :casgn
  report_cross_file_collision(node, name, constant_display_name(node))
end

#on_class(node) ⇒ Object



95
96
97
98
99
# File 'lib/rubocop/cop/lint/constant_reassignment.rb', line 95

def on_class(node)
  return unless unconditional_definition?(node)

  constant_definitions[definition_name(node)] ||= :class
end

#on_module(node) ⇒ Object



101
102
103
104
105
# File 'lib/rubocop/cop/lint/constant_reassignment.rb', line 101

def on_module(node)
  return unless unconditional_definition?(node)

  constant_definitions[definition_name(node)] ||= :module
end

#on_send(node) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
# File 'lib/rubocop/cop/lint/constant_reassignment.rb', line 122

def on_send(node)
  constant = remove_constant(node)

  return unless constant

  namespaces = ancestor_namespaces(node)

  return if namespaces.none?

  constant_definitions.delete(fully_qualified_name_for(namespaces, constant))
end

#remove_constant(node) ⇒ Object



90
91
92
93
# File 'lib/rubocop/cop/lint/constant_reassignment.rb', line 90

def_node_matcher :remove_constant, <<~PATTERN
  (send {nil? self} :remove_const
    ({sym str} $_))
PATTERN