aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/attribute_set.rb
blob: 228e82f33201cc547622886de7d55d3082457c42 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
require 'active_record/attribute_set/builder'

module ActiveRecord
  class AttributeSet # :nodoc:
    delegate :[], :[]=, :each_with_object, to: :attributes
    delegate :keys, to: :initialized_attributes

    def initialize(attributes)
      @attributes = attributes
    end

    def to_hash
      initialized_attributes.each_with_object({}) { |(k, v), h| h[k] = v.value }
    end
    alias_method :to_h, :to_hash

    def include?(name)
      attributes.include?(name) && self[name].initialized?
    end

    def fetch_value(name)
      attribute = self[name]
      if attribute.initialized? || !block_given?
        attribute.value
      else
        yield name
      end
    end

    def freeze
      @attributes.freeze
      super
    end

    def initialize_dup(_)
      @attributes = attributes.dup
      attributes.each do |key, attr|
        attributes[key] = attr.dup
      end

      super
    end

    def initialize_clone(_)
      @attributes = attributes.clone
      super
    end

    protected

    attr_reader :attributes

    private

    def initialized_attributes
      attributes.select { |_, attr| attr.initialized? }
    end
  end
end