aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/type_caster/connection.rb
blob: 1d204edb76b20a32c3853cf8cd252d6f4077a6b0 (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
module ActiveRecord
  module TypeCaster
    class Connection
      def initialize(klass, table_name)
        @klass = klass
        @table_name = table_name
      end

      def type_cast_for_database(attribute_name, value)
        return value if value.is_a?(Arel::Nodes::BindParam)
        type = type_for(attribute_name)
        type.type_cast_for_database(value)
      end

      protected

      attr_reader :table_name
      delegate :connection, to: :@klass

      private

      def type_for(attribute_name)
        if connection.schema_cache.table_exists?(table_name)
          column_for(attribute_name).cast_type
        else
          Type::Value.new
        end
      end

      def column_for(attribute_name)
        connection.schema_cache.columns_hash(table_name)[attribute_name.to_s]
      end
    end
  end
end