Sha256: 84cbbbb7774954dcf49191c02f6c615d1acc63f132ea6a6660a38ed9a71ad51d

Contents?: true

Size: 1.79 KB

Versions: 13

Compression:

Stored size: 1.79 KB

Contents

module Rasti
  module DB
    module TypeConverters
      class Postgres

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

        @to_db_mapping = {}

        class << self

          def to_db(db, collection_name, attribute_name, value)
            to_db_mapping = to_db_mapping_for db, collection_name

            if to_db_mapping.key? attribute_name
              to_db_mapping[attribute_name][:converter].to_db value, to_db_mapping[attribute_name][:sub_type]
            else
              value
            end
          end

          def from_db(object)
            if from_db_mapping.key? object.class
              from_db_mapping[object.class].from_db object
            else
              object
            end
          end

          private

          def to_db_mapping_for(db, collection_name)
            key = [db.opts[:database], collection_name]
            
            @to_db_mapping[key] ||= begin
              columns = Hash[db.schema(collection_name)]

              columns.each_with_object({}) do |(name, schema), hash| 
                CONVERTERS.each do |converter|
                  unless hash.key? name
                    match = converter.column_type_regex.match schema[:db_type]

                    hash[name] = {converter: converter, sub_type: match.captures.first} if match
                  end
                end
              end
            end
          end

          def from_db_mapping
            @from_db_mapping ||= begin
              CONVERTERS.each_with_object({}) do |converter, result|
                converter.db_classes.each do |db_class|
                  result[db_class] = converter
                end
              end              
            end
          end

        end

      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
rasti-db-2.3.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-2.2.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-2.1.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-2.0.1 lib/rasti/db/type_converters/postgres.rb
rasti-db-2.0.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-1.5.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-1.4.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-1.3.1 lib/rasti/db/type_converters/postgres.rb
rasti-db-1.3.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-1.2.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-1.1.1 lib/rasti/db/type_converters/postgres.rb
rasti-db-1.1.0 lib/rasti/db/type_converters/postgres.rb
rasti-db-1.0.0 lib/rasti/db/type_converters/postgres.rb