Class: ActiveRecord::LazyAttributeHash

Inherits:
Object
  • Object
show all
Defined in:
activerecord/lib/active_record/attribute_set/builder.rb

Overview

:nodoc:

Instance Method Summary collapse

Constructor Details

#initialize(types, values, additional_types, &default) ⇒ LazyAttributeHash

Returns a new instance of LazyAttributeHash.



30
31
32
33
34
35
36
37
# File 'activerecord/lib/active_record/attribute_set/builder.rb', line 30

def initialize(types, values, additional_types, &default)
  @types = types
  @values = values
  @additional_types = additional_types
  @materialized = false
  @delegate_hash = {}
  @default = default || proc {}
end

Instance Method Details

#==(other) ⇒ Object



75
76
77
78
79
80
81
# File 'activerecord/lib/active_record/attribute_set/builder.rb', line 75

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

#[](key) ⇒ Object



43
44
45
# File 'activerecord/lib/active_record/attribute_set/builder.rb', line 43

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

#[]=(key, value) ⇒ Object



47
48
49
50
51
52
# File 'activerecord/lib/active_record/attribute_set/builder.rb', line 47

def []=(key, value)
  if frozen?
    raise RuntimeError, "Can't modify frozen hash"
  end
  delegate_hash[key] = value
end

#deep_dupObject



54
55
56
57
58
# File 'activerecord/lib/active_record/attribute_set/builder.rb', line 54

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

#initialize_dup(_) ⇒ Object



60
61
62
63
# File 'activerecord/lib/active_record/attribute_set/builder.rb', line 60

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

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'activerecord/lib/active_record/attribute_set/builder.rb', line 39

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

#marshal_dumpObject



83
84
85
# File 'activerecord/lib/active_record/attribute_set/builder.rb', line 83

def marshal_dump
  materialize
end

#marshal_load(delegate_hash) ⇒ Object



87
88
89
90
91
92
93
# File 'activerecord/lib/active_record/attribute_set/builder.rb', line 87

def marshal_load(delegate_hash)
  @delegate_hash = delegate_hash
  @types = {}
  @values = {}
  @additional_types = {}
  @materialized = true
end

#selectObject



65
66
67
68
69
70
71
72
73
# File 'activerecord/lib/active_record/attribute_set/builder.rb', line 65

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