Class: ActiveRecord::LazyAttributeHash

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/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.



23
24
25
26
27
28
29
30
# File 'lib/active_record/attribute_set/builder.rb', line 23

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



68
69
70
71
72
73
74
# File 'lib/active_record/attribute_set/builder.rb', line 68

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

#[](key) ⇒ Object



36
37
38
# File 'lib/active_record/attribute_set/builder.rb', line 36

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

#[]=(key, value) ⇒ Object



40
41
42
43
44
45
# File 'lib/active_record/attribute_set/builder.rb', line 40

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

#deep_dupObject



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

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

#initialize_dup(_) ⇒ Object



53
54
55
56
# File 'lib/active_record/attribute_set/builder.rb', line 53

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

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/active_record/attribute_set/builder.rb', line 32

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

#marshal_dumpObject



76
77
78
# File 'lib/active_record/attribute_set/builder.rb', line 76

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

#marshal_load(values) ⇒ Object



80
81
82
83
84
85
86
87
88
# File 'lib/active_record/attribute_set/builder.rb', line 80

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



58
59
60
61
62
63
64
65
66
# File 'lib/active_record/attribute_set/builder.rb', line 58

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