Sha256: c309b707fd95771b18714d44bbe19061270a6ceaabc4197cdc4a79a9ca4d6deb

Contents?: true

Size: 1.51 KB

Versions: 1

Compression:

Stored size: 1.51 KB

Contents

# encoding: utf-8

begin
  require "mongo"
rescue LoadError
  puts "You need the mongo gem to use the MongoDB moneta store"
  exit
end
require 'uri'

module Moneta
  module Adapters
    class MongoDB
      include Moneta::Defaults

      def initialize(options = {})
        if options[:uri]
          conn = Mongo::Connection.from_uri options[:uri]
          db_name = URI.parse(options[:uri]).path.sub('/','')
          db_name ||= options[:db]
        else
          options = {
            :host => ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost',
            :port => ENV['MONGO_RUBY_DRIVER_PORT'] || Mongo::Connection::DEFAULT_PORT,
            :db => 'cache',
            :collection => 'cache'
          }.update(options)
          conn = Mongo::Connection.new(options[:host], options[:port])
          db_name = options[:db]
        end
        db = conn.db(db_name)
        @cache = db.collection(options[:collection])
      end

      def key?(key, *)
        !!self[key]
      end

      def [](key)
        res = @cache.find_one('_id' => key_for(key))
        res ? res['data'] : nil
      end

      def delete(key, *)
        string_key = key_for(key)

        value = self[key]
        @cache.remove('_id' => string_key) if value
        value
      end

      def store(key, value, *)
        key = key_for(key)
        @cache.update({ '_id' => key },
                      { '_id' => key, 'data' => value },
                      { :upsert => true })
      end

      def clear(*)
        @cache.remove
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dkastner-moneta-1.1.0 lib/moneta/adapters/mongodb.rb