aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/attribute_set/builder.rb
blob: d91720d5e11c4a3ca99082182de25b06e576ad78 (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
module ActiveRecord
  class AttributeSet # :nodoc:
    class Builder # :nodoc:
      attr_reader :types

      def initialize(types)
        @types = types
      end

      def build_from_database(values, additional_types = {})
        attributes = build_attributes_from_values(values, additional_types)
        add_uninitialized_attributes(attributes)
        AttributeSet.new(attributes)
      end

      private

      def build_attributes_from_values(values, additional_types)
        attributes = Hash.new(Attribute::Null)
        values.each_with_object(attributes) do |(name, value), hash|
          type = additional_types.fetch(name, types[name])
          hash[name] = Attribute.from_database(value, type)
        end
      end

      def add_uninitialized_attributes(attributes)
        types.except(*attributes.keys).each do |name, type|
          attributes[name] = Attribute.uninitialized(type)
        end
      end
    end
  end
end