aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/type_caster/connection.rb
blob: f43559f4cb8de214621696c20f975f0768953483 (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
# frozen_string_literal: true

module ActiveRecord
  module TypeCaster
    class Connection # :nodoc:
      def initialize(klass, table_name)
        @klass = klass
        @table_name = table_name
      end

      def type_cast_for_database(attr_name, value)
        return value if value.is_a?(Arel::Nodes::BindParam)
        type = type_for_attribute(attr_name)
        type.serialize(value)
      end

      def type_for_attribute(attr_name)
        schema_cache = connection.schema_cache

        if schema_cache.data_source_exists?(table_name)
          column = schema_cache.columns_hash(table_name)[attr_name.to_s]
          type = connection.lookup_cast_type_from_column(column) if column
        end

        type || Type.default_value
      end

      delegate :connection, to: :@klass, private: true

      private
        attr_reader :table_name
    end
  end
end