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

      def initialize(types)
        @types = types
      end

      def build_from_database(values = {}, additional_types = {})
        build_from_database_pairs(values.keys, values.values, additional_types)
      end

      def build_from_database_pairs(columns, values, additional_types)
        attributes = build_attributes_from_values(columns, values, additional_types)
        add_uninitialized_attributes(attributes)
        AttributeSet.new(attributes)
      end

      private

      def build_attributes_from_values(columns, values, additional_types)
        # We are performing manual iteration here as this method is a performance
        # hotspot
        hash = {}
        index = 0
        length = columns.length

        while index < length
          name = columns[index]
          value = values[index]
          type = additional_types.fetch(name, types[name])
          hash[name] = Attribute.from_database(name, value, type)
          index += 1
        end

        hash
      end

      def add_uninitialized_attributes(attributes)
        types.each_key do |name|
          next if attributes.key? name
          type = types[name]
          attributes[name] =
            Attribute.uninitialized(name, type)
        end
      end
    end
  end
end