Sha256: 687f0950e1d2381d8fd2c7caeee6ffafad7f693054b1cc9022f77574ab85c958

Contents?: true

Size: 1.5 KB

Versions: 9

Compression:

Stored size: 1.5 KB

Contents

module Rasti
  module DB
    module TypeConverters
      class SQLite

        CONVERTERS = [SQLiteTypes::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
            else
              value
            end
          end

          def from_db(object)
            converter = find_converter_from_db object
            if !converter.nil?
              converter.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 } if match
                  end
                end
              end
            end
          end

          def find_converter_from_db(object)
            CONVERTERS.find do |converter|
              converter.respond_for? object
            end
          end

        end

      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

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