Class: Moneta::Adapters::MongoOfficial

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

Overview

MongoDB backend

Supports expiration, documents will be automatically removed starting with mongodb >= 2.2 (see /).

You can store hashes directly using this adapter.

Examples:

Store hashes

db = Moneta::Adapters::MongoOfficial.new
db['key'] = {a: 1, b: 2}

Constant Summary

Constants inherited from MongoBase

Moneta::Adapters::MongoBase::DEFAULT_PORT

Instance Attribute Summary

Attributes inherited from MongoBase

#backend

Attributes included from ExpiresSupport

#default_expires

Instance Method Summary collapse

Methods included from Defaults

#[], #[]=, #decrement, #features, #fetch, included, #key?, #supports?

Methods included from OptionSupport

#expires, #prefix, #raw, #with

Constructor Details

#initialize(options = {}) ⇒ MongoOfficial

Returns a new instance of MongoOfficial.

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

  • :user (String)

    Username used to authenticate

  • :password (String)

    Password used to authenticate

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

    MongoDB server port

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

    MongoDB database

  • :expires (Integer)

    Default expiration time

  • :expires_field (String) — default: 'expiresAt'

    Document field to store expiration time

  • :value_field (String) — default: 'value'

    Document field to store value

  • :type_field (String) — default: 'type'

    Document field to store value type

  • :backend (::Mongo::MongoClient)

    Use existing backend instance

  • Other (Object)

    options passed to `Mongo::MongoClient#new`


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/moneta/adapters/mongo/official.rb', line 32

def initialize(options = {})
  super(options)
  collection = options.delete(:collection) || 'moneta'
  db = options.delete(:db) || 'moneta'
  user = options.delete(:user)
  password = options.delete(:password)
  @backend = options[:backend] ||
    begin
      host = options.delete(:host) || '127.0.0.1'
      port = options.delete(:port) || ::Mongo::MongoClient::DEFAULT_PORT
      ::Mongo::MongoClient.new(host, port, options)
    end
  db = @backend.db(db)
  db.authenticate(user, password, true) if user && password
  @collection = db.collection(collection)
  if @backend.server_version >= '2.2'
    @collection.ensure_index([[@expires_field, ::Mongo::ASCENDING]], expireAfterSeconds: 0)
  else
    warn 'Moneta::Adapters::Mongo - You are using MongoDB version < 2.2, expired documents will not be deleted'
  end
end

Instance Method Details

#clear(options = {}) ⇒ void

This method returns an undefined value.

Clear all keys in this store

Parameters:

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

102
103
104
105
# File 'lib/moneta/adapters/mongo/official.rb', line 102

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

#closeObject

Explicitly close the store

Returns:

  • nil


108
109
110
111
# File 'lib/moneta/adapters/mongo/official.rb', line 108

def close
  @backend.close
  nil
end

#create(key, value, options = {}) ⇒ Boolean

Note:

Not every Moneta store implements this method, a NotImplementedError is raised if it is not supported.

Atomically sets a key to value if it's not set.

Parameters:

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

Options Hash (options):

  • :expires (Integer)

    Update expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

Returns:

  • (Boolean)

    key was set


92
93
94
95
96
97
98
99
# File 'lib/moneta/adapters/mongo/official.rb', line 92

def create(key, value, options = {})
  key = to_binary(key)
  @collection.insert(value_to_doc(key, value, options))
  true
rescue ::Mongo::OperationFailure => ex
  raise if ex.error_code != 11000 # duplicate key error
  false
end

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

Delete the key from the store and return the current value

Parameters:

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

Options Hash (options):

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Object)

    current value


77
78
79
80
81
# File 'lib/moneta/adapters/mongo/official.rb', line 77

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

#increment(key, amount = 1, options = {}) ⇒ Object

Note:

Not every Moneta store implements this method, a NotImplementedError is raised if it is not supported.

Atomically increment integer value with key

This method also accepts negative amounts.

Parameters:

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

Options Hash (options):

  • :prefix (String)

    Prefix key (See Transformer)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Object)

    value from store


84
85
86
87
88
89
# File 'lib/moneta/adapters/mongo/official.rb', line 84

def increment(key, amount = 1, options = {})
  @collection.find_and_modify(query: { '_id' => to_binary(key) },
                              update: { '$inc' => { @value_field => amount } },
                              new: true,
                              upsert: true)[@value_field]
end

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

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

Parameters:

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

Options Hash (options):

  • :expires (Integer)

    Update expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • :sync (Boolean)

    Synchronized load (Cache reloads from adapter, Daybreak syncs with file)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Object)

    value


55
56
57
58
59
60
61
62
63
64
65
# File 'lib/moneta/adapters/mongo/official.rb', line 55

def load(key, options = {})
  key = to_binary(key)
  doc = @collection.find_one('_id' => key)
  if doc && (!doc[@expires_field] || doc[@expires_field] >= Time.now)
    expires = expires_at(options, nil)
    @collection.update({ '_id' => key },
                       # @expires_field must be a Time object (BSON date datatype)
                       { '$set' => { @expires_field => expires || nil } }) if expires != nil
    doc_to_value(doc)
  end
end

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

Store value with key

Parameters:

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

Options Hash (options):

  • :expires (Integer)

    Set expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • value


68
69
70
71
72
73
74
# File 'lib/moneta/adapters/mongo/official.rb', line 68

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