Class: Moneta::Adapters::Mongo

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

Overview

MongoDB backend

Instance Method Summary collapse

Methods included from Defaults

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

Methods included from OptionSupport

#expires, #prefix, #raw, #with

Constructor Details

#initialize(options = {}) ⇒ Mongo

Returns a new instance of Mongo.

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 = {}) ⇒ void

This method returns an undefined value.

Clear all keys in this store

Parameters:

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


47
48
49
50
# File 'lib/moneta/adapters/mongo.rb', line 47

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

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

Delete the key from the store and return the current value

Parameters:

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

Returns:

  • (Object)

    current value



31
32
33
34
35
# File 'lib/moneta/adapters/mongo.rb', line 31

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

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

Fetch value with key. Return nil if the key doesn’t exist

Parameters:

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

Returns:

  • (Object)

    value



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

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

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

Store value with key

Parameters:

  • key (Object)
  • value (Object)
  • options (Hash) (defaults to: {})

Returns:

  • value



38
39
40
41
42
43
44
# File 'lib/moneta/adapters/mongo.rb', line 38

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