Class: Moneta::Adapters::Mongo

Inherits:
Base
  • Object
show all
Defined in:
lib/moneta/adapters/mongo.rb

Overview

MongoDB backend

Instance Method Summary collapse

Methods inherited from Base

#[], #[]=, #close, #decrement, #fetch, #increment, #key?

Methods included from Mixins::WithOptions

#expires, #prefix, #raw, #with

Constructor Details

#initialize(options = {}) ⇒ Mongo

Constructor

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :collection (String) — default: 'moneta'

    MongoDB collection name

  • :host (String) — default: '127.0.0.1'

    MongoDB server host

  • :port (Integer) — default: MongoDB default port

    MongoDB server port

  • :db (String) — default: 'moneta'

    MongoDB database



15
16
17
18
19
20
21
22
# File 'lib/moneta/adapters/mongo.rb', line 15

def initialize(options = {})
  collection = options.delete(:collection) || 'moneta'
  host = options.delete(:host) || '127.0.0.1'
  port = options.delete(:port) || ::Mongo::Connection::DEFAULT_PORT
  db = options.delete(:db) || 'moneta'
  connection = ::Mongo::Connection.new(host, port, options)
  @collection = connection.db(db).collection(collection)
end

Instance Method Details

#clear(options = {}) ⇒ Object



43
44
45
46
# File 'lib/moneta/adapters/mongo.rb', line 43

def clear(options = {})
  @collection.remove
  self
end

#delete(key, options = {}) ⇒ Object



29
30
31
32
33
# File 'lib/moneta/adapters/mongo.rb', line 29

def delete(key, options = {})
  value = load(key, options)
  @collection.remove('_id' => ::BSON::Binary.new(key)) if value
  value
end

#load(key, options = {}) ⇒ Object



24
25
26
27
# File 'lib/moneta/adapters/mongo.rb', line 24

def load(key, options = {})
  value = @collection.find_one('_id' => ::BSON::Binary.new(key))
  value && value['value'].to_s
end

#store(key, value, options = {}) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/moneta/adapters/mongo.rb', line 35

def store(key, value, options = {})
  key = ::BSON::Binary.new(key)
  @collection.update({ '_id' => key },
                     { '_id' => key, 'value' => ::BSON::Binary.new(value) },
                     { :upsert => true })
  value
end