Class: RuboCop::Cop::Lint::SharedMutableDefault

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

Overview

Checks for ‘Hash` creation with a mutable default value. Creating a `Hash` in such a way will share the default value across all keys, causing unexpected behavior when modifying it.

For example, when the ‘Hash` was created with an `Array` as the argument, calling `hash << ’bar’‘ will also change the value of all other keys that have not been explicitly assigned to.

Examples:

# bad
Hash.new([])
Hash.new({})
Hash.new(Array.new)
Hash.new(Hash.new)

# okay -- In rare cases that intentionally have this behavior,
#   without disabling the cop, you can set the default explicitly.
h = Hash.new
h.default = []
h[:a] << 1
h[:b] << 2
h # => {:a => [1, 2], :b => [1, 2]}

# okay -- beware this will discard mutations and only remember assignments
Hash.new { Array.new }
Hash.new { Hash.new }
Hash.new { {} }
Hash.new { [] }

# good - frozen solution will raise an error when mutation attempted
Hash.new([].freeze)
Hash.new({}.freeze)

# good - using a proc will create a new object for each key
h = Hash.new
h.default_proc = ->(h, k) { [] }
h.default_proc = ->(h, k) { {} }

# good - using a block will create a new object for each key
Hash.new { |h, k| h[k] = [] }
Hash.new { |h, k| h[k] = {} }

Constant Summary collapse

MSG =
'Do not create a Hash with a mutable default value ' \
'as the default value can accidentally be changed.'
RESTRICT_ON_SEND =
%i[new].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

#capacity_keyword_argument?(node) ⇒ Object

[View source]

64
65
66
# File 'lib/rubocop/cop/lint/shared_mutable_default.rb', line 64

def_node_matcher :capacity_keyword_argument?, <<~PATTERN
  (hash (pair (sym :capacity) _))
PATTERN

#hash_initialized_with_mutable_shared_object?(node) ⇒ Object

[View source]

53
54
55
56
57
58
59
60
61
# File 'lib/rubocop/cop/lint/shared_mutable_default.rb', line 53

def_node_matcher :hash_initialized_with_mutable_shared_object?, <<~PATTERN
  {
    (send (const {nil? cbase} :Hash) :new [
      {array hash (send (const {nil? cbase} {:Array :Hash}) :new)}
      !#capacity_keyword_argument?
    ])
    (send (const {nil? cbase} :Hash) :new hash #capacity_keyword_argument?)
  }
PATTERN

#on_send(node) ⇒ Object

[View source]

68
69
70
71
72
# File 'lib/rubocop/cop/lint/shared_mutable_default.rb', line 68

def on_send(node)
  return unless hash_initialized_with_mutable_shared_object?(node)

  add_offense(node)
end