Sha256: 1e90bc8214e876c6cfc6b2342b11909c419d0a3b348cc11fb893f27f12247e43

Contents?: true

Size: 1.68 KB

Versions: 7

Compression:

Stored size: 1.68 KB

Contents

module Rasti
  module DB
    module TypeConverters
      class Postgres

        CONVERTERS = [
          PostgresTypes::JSON,
          PostgresTypes::JSONB,
          PostgresTypes::HStore,
          PostgresTypes::Array
        ]

        class << self

          def to_db(db, collection_name, attribute_name, value)
            converter, type = find_to_db_converter_and_type db, collection_name, attribute_name
            converter ? converter.to_db(value, type) : value
          end

          def from_db(value)
            converter = find_from_db_converter value.class
            converter ? converter.from_db(value) : value
          end

          private

          def from_db_converters
            @from_db_converters ||= {}
          end

          def to_db_converters
            @to_db_converters ||= {}
          end

          def find_to_db_converter_and_type(db, collection_name, attribute_name)
            key = [db.opts[:database], collection_name]

            to_db_converters[key] ||= begin
              columns = Hash[db.schema(collection_name)]
              to_db_converters[key] = columns.each_with_object({}) do |(name, schema), hash|
                converter = CONVERTERS.detect { |c| c.to_db? schema[:db_type] }
                hash[name] = [converter, schema[:db_type]] if converter
              end
            end

            to_db_converters[key].fetch(attribute_name, [])
          end

          def find_from_db_converter(klass)
            if !from_db_converters.key?(klass)
              from_db_converters[klass] = CONVERTERS.detect { |c| c.from_db? klass }
            end

            from_db_converters[klass]
          end

        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
rasti-db-4.2.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-4.1.1 lib/rasti/db/type_converters/postgres.rb
rasti-db-4.1.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-4.0.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-3.0.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-2.3.3 lib/rasti/db/type_converters/postgres.rb
rasti-db-2.3.2 lib/rasti/db/type_converters/postgres.rb