Class: ActiveModel::LazyAttributeHash

Inherits:
Object
  • Object
show all
Defined in:
activemodel/lib/active_model/attribute_set/builder.rb

Overview

:nodoc:

Instance Method Summary collapse

Constructor Details

#initialize(types, values, additional_types, default_attributes, delegate_hash = {}) ⇒ LazyAttributeHash

Returns a new instance of LazyAttributeHash.


25
26
27
28
29
30
31
32
# File 'activemodel/lib/active_model/attribute_set/builder.rb', line 25

def initialize(types, values, additional_types, default_attributes, delegate_hash = {})
  @types = types
  @values = values
  @additional_types = additional_types
  @materialized = false
  @delegate_hash = delegate_hash
  @default_attributes = default_attributes
end

Instance Method Details

#==(other) ⇒ Object


67
68
69
70
71
72
73
# File 'activemodel/lib/active_model/attribute_set/builder.rb', line 67

def ==(other)
  if other.is_a?(LazyAttributeHash)
    materialize == other.materialize
  else
    materialize == other
  end
end

#[](key) ⇒ Object


38
39
40
# File 'activemodel/lib/active_model/attribute_set/builder.rb', line 38

def [](key)
  delegate_hash[key] || assign_default_value(key)
end

#[]=(key, value) ⇒ Object


42
43
44
# File 'activemodel/lib/active_model/attribute_set/builder.rb', line 42

def []=(key, value)
  delegate_hash[key] = value
end

#deep_dupObject


46
47
48
49
50
# File 'activemodel/lib/active_model/attribute_set/builder.rb', line 46

def deep_dup
  dup.tap do |copy|
    copy.instance_variable_set(:@delegate_hash, delegate_hash.transform_values(&:dup))
  end
end

#initialize_dup(_) ⇒ Object


52
53
54
55
# File 'activemodel/lib/active_model/attribute_set/builder.rb', line 52

def initialize_dup(_)
  @delegate_hash = Hash[delegate_hash]
  super
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)

34
35
36
# File 'activemodel/lib/active_model/attribute_set/builder.rb', line 34

def key?(key)
  delegate_hash.key?(key) || values.key?(key) || types.key?(key)
end

#marshal_dumpObject


75
76
77
# File 'activemodel/lib/active_model/attribute_set/builder.rb', line 75

def marshal_dump
  [@types, @values, @additional_types, @default_attributes, @delegate_hash]
end

#marshal_load(values) ⇒ Object


79
80
81
82
83
84
85
86
87
# File 'activemodel/lib/active_model/attribute_set/builder.rb', line 79

def marshal_load(values)
  if values.is_a?(Hash)
    empty_hash = {}.freeze
    initialize(empty_hash, empty_hash, empty_hash, empty_hash, values)
    @materialized = true
  else
    initialize(*values)
  end
end

#selectObject


57
58
59
60
61
62
63
64
65
# File 'activemodel/lib/active_model/attribute_set/builder.rb', line 57

def select
  keys = types.keys | values.keys | delegate_hash.keys
  keys.each_with_object({}) do |key, hash|
    attribute = self[key]
    if yield(key, attribute)
      hash[key] = attribute
    end
  end
end