Class: Chef::Node::ImmutableArray

Inherits:
Array
  • Object
show all
Includes:
Immutablize
Defined in:
lib/chef/node/immutable_collections.rb

Overview

ImmutableArray

ImmutableArray is used to implement Array collections when reading node attributes.

ImmutableArray acts like an ordinary Array, except:

  • Methods that mutate the array are overridden to raise an error, making the collection more or less immutable.

  • Since this class stores values computed from a parent Chef::Node::Attribute’s values, it overrides all reader methods to detect staleness and raise an error if accessed when stale.

Constant Summary collapse

DISALLOWED_MUTATOR_METHODS =

A list of methods that mutate Array. Each of these is overridden to raise an error, making this instances of this class more or less immutable.

[
  :<<,
  :[]=,
  :clear,
  :collect!,
  :compact!,
  :default=,
  :default_proc=,
  :delete,
  :delete_at,
  :delete_if,
  :fill,
  :flatten!,
  :insert,
  :keep_if,
  :map!,
  :merge!,
  :pop,
  :push,
  :update,
  :reject!,
  :reverse!,
  :replace,
  :select!,
  :shift,
  :slice!,
  :sort!,
  :sort_by!,
  :uniq!,
  :unshift,
]

Instance Method Summary collapse

Methods included from Immutablize

#immutablize

Constructor Details

#initialize(array_data) ⇒ ImmutableArray

Returns a new instance of ImmutableArray.



87
88
89
90
91
# File 'lib/chef/node/immutable_collections.rb', line 87

def initialize(array_data)
  array_data.each do |value|
    internal_push(immutablize(value))
  end
end

Instance Method Details

#dupObject



108
109
110
# File 'lib/chef/node/immutable_collections.rb', line 108

def dup
  Array.new(map { |e| safe_dup(e) })
end

#safe_dup(e) ⇒ Object

For elements like Fixnums, true, nil…



102
103
104
105
106
# File 'lib/chef/node/immutable_collections.rb', line 102

def safe_dup(e)
  e.dup
rescue TypeError
  e
end

#to_aObject



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/chef/node/immutable_collections.rb', line 112

def to_a
  a = Array.new
  each do |v|
    a <<
      case v
      when ImmutableArray
        v.to_a
      when ImmutableMash
        v.to_hash
      else
        v
      end
  end
  a
end