Class: Moneta::Adapters::Mongo
- Inherits:
-
Moneta::Adapter
- Object
- Moneta::Adapter
- Moneta::Adapters::Mongo
- Includes:
- ExpiresSupport
- Defined in:
- lib/moneta/adapters/mongo.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.
Instance Attribute Summary
Attributes inherited from Moneta::Adapter
Instance Method Summary collapse
-
#clear(options = {}) ⇒ void
Clear all keys in this store.
-
#close ⇒ Object
Explicitly close the store.
-
#create(key, value, options = {}) ⇒ Boolean
Atomically sets a key to value if it’s not set.
-
#delete(key, options = {}) ⇒ Object
Delete the key from the store and return the current value.
-
#each_key ⇒ Object
Calls block once for each key in store, passing the key as a parameter.
-
#fetch_values(*keys, **options) ⇒ Object
Behaves identically to #values_at except that it accepts an optional block.
-
#increment(key, amount = 1, options = {}) ⇒ Object
Atomically increment integer value with key.
-
#initialize(options = {}) ⇒ Mongo
constructor
A new instance of Mongo.
-
#load(key, options = {}) ⇒ Object
Fetch value with key.
-
#merge!(pairs, options = {}) ⇒ Object
Stores the pairs in the key-value store, and returns itself.
-
#slice(*keys, **options) ⇒ <(Object, Object)>
Returns a collection of key-value pairs corresponding to those supplied keys which are present in the key-value store, and their associated values.
-
#store(key, value, options = {}) ⇒ Object
Store value with key.
-
#values_at(*keys, **options) ⇒ Array<Object, nil>
Returns an array containing the values associated with the given keys, in the same order as the supplied keys.
Methods included from ExpiresSupport
Methods inherited from Moneta::Adapter
backend, backend_block, backend_required?
Methods included from Config
Methods included from Defaults
#[], #[]=, #decrement, #features, #fetch, included, #key?, #supports?, #update
Methods included from OptionSupport
#expires, #prefix, #raw, #with
Constructor Details
#initialize(options = {}) ⇒ Mongo
Returns a new instance of Mongo.
58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/moneta/adapters/mongo.rb', line 58 def initialize( = {}) super @database = backend.use(config.database) @collection = @database[config.collection] if @database.command(buildinfo: 1).documents.first['version'] >= '2.2' @collection.indexes.create_one({ config.expires_field => 1 }, expire_after: 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
136 137 138 139 |
# File 'lib/moneta/adapters/mongo.rb', line 136 def clear( = {}) @collection.delete_many self end |
#close ⇒ Object
Explicitly close the store
142 143 144 145 |
# File 'lib/moneta/adapters/mongo.rb', line 142 def close @database.close nil end |
#create(key, value, options = {}) ⇒ Boolean
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.
126 127 128 129 130 131 132 133 |
# File 'lib/moneta/adapters/mongo.rb', line 126 def create(key, value, = {}) key = to_binary(key) @collection.insert_one(value_to_doc(key, value, )) true rescue ::Mongo::Error::OperationFailure => error raise unless error.code == 11000 # duplicate key error false end |
#delete(key, options = {}) ⇒ Object
Delete the key from the store and return the current value
106 107 108 109 110 111 112 |
# File 'lib/moneta/adapters/mongo.rb', line 106 def delete(key, = {}) key = to_binary(key) if doc = @collection.find(_id: key).find_one_and_delete and !doc[config.expires_field] || doc[config.expires_field] >= Time.now doc_to_value(doc) end end |
#each_key ⇒ Enumerator #each_key {|key| ... } ⇒ self
Not every Moneta store implements this method, a NotImplementedError is raised if it is not supported.
Calls block once for each key in store, passing the key as a parameter. If no block is given, an enumerator is returned instead.
99 100 101 102 103 |
# File 'lib/moneta/adapters/mongo.rb', line 99 def each_key return enum_for(:each_key) unless block_given? @collection.find.each { |doc| yield from_binary(doc[:_id]) } self end |
#fetch_values(*keys, **options) ⇒ Object #fetch_values(*keys, **options) {|key| ... } ⇒ Array<Object, nil>
Some adapters may implement this method atomically. The default implmentation uses #values_at.
Behaves identically to #values_at except that it accepts an optional block. When supplied, the block will be called successively with each supplied key that is not present in the store. The return value of the block call will be used in place of nil in returned the array of values.
183 184 185 186 187 188 189 190 191 192 193 |
# File 'lib/moneta/adapters/mongo.rb', line 183 def fetch_values(*keys, **) return values_at(*keys, **) unless block_given? hash = Hash[slice(*keys, **)] keys.map do |key| if hash.key?(key) hash[key] else yield key end end end |
#increment(key, amount = 1, options = {}) ⇒ Object
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.
115 116 117 118 119 120 121 122 123 |
# File 'lib/moneta/adapters/mongo.rb', line 115 def increment(key, amount = 1, = {}) @collection.find_one_and_update({ :$and => [{ _id: to_binary(key) }, not_expired] }, { :$inc => { config.value_field => amount } }, return_document: :after, upsert: true)[config.value_field] rescue ::Mongo::Error::OperationFailure tries ||= 0 (tries += 1) < 3 ? retry : raise end |
#load(key, options = {}) ⇒ Object
Fetch value with key. Return nil if the key doesn’t exist
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/moneta/adapters/mongo.rb', line 72 def load(key, = {}) view = @collection.find(:$and => [ { _id: to_binary(key) }, not_expired ]) doc = view.limit(1).first if doc update_expiry(, nil) do |expires| view.update_one(:$set => { config.expires_field => expires }) end doc_to_value(doc) end end |
#merge!(pairs, options = {}) ⇒ self #merge!(pairs, options = {}) {|key, old_value, new_value| ... } ⇒ self
Some adapters may implement this method atomically, or in two passes when a block is provided. The default implmentation uses Defaults#key?, #load and #store.
Stores the pairs in the key-value store, and returns itself. When a block is provided, it will be called before overwriting any existing values with the key, old value and supplied value, and the return value of the block will be used in place of the supplied value.
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
# File 'lib/moneta/adapters/mongo.rb', line 163 def merge!(pairs, = {}) existing = Hash[slice(*pairs.map { |key, _| key })] update_pairs, insert_pairs = pairs.partition { |key, _| existing.key?(key) } unless insert_pairs.empty? @collection.insert_many(insert_pairs.map do |key, value| value_to_doc(to_binary(key), value, ) end) end update_pairs.each do |key, value| value = yield(key, existing[key], value) if block_given? binary = to_binary(key) @collection.replace_one({ _id: binary }, value_to_doc(binary, value, )) end self end |
#slice(*keys, **options) ⇒ <(Object, Object)>
The keys in the return value may be the same objects that were supplied (i.e. Object#equal?), or may simply be equal (i.e. Object#==).
Some adapters may implement this method atomically. The default implmentation uses #values_at.
Returns a collection of key-value pairs corresponding to those supplied keys which are present in the key-value store, and their associated values. Only those keys present in the store will have pairs in the return value. The return value can be any enumerable object that yields pairs, so it could be a hash, but needn’t be.
148 149 150 151 152 153 154 155 156 157 158 159 160 |
# File 'lib/moneta/adapters/mongo.rb', line 148 def slice(*keys, **) view = @collection.find(:$and => [ { _id: { :$in => keys.map(&method(:to_binary)) } }, not_expired ]) pairs = view.map { |doc| [from_binary(doc[:_id]), doc_to_value(doc)] } update_expiry(, nil) do |expires| view.update_many(:$set => { config.expires_field => expires }) end pairs end |
#store(key, value, options = {}) ⇒ Object
Store value with key
90 91 92 93 94 95 96 |
# File 'lib/moneta/adapters/mongo.rb', line 90 def store(key, value, = {}) key = to_binary(key) @collection.replace_one({ _id: key }, value_to_doc(key, value, ), upsert: true) value end |
#values_at(*keys, **options) ⇒ Array<Object, nil>
Some adapters may implement this method atomically, but the default implementation simply makes repeated calls to #load.
Returns an array containing the values associated with the given keys, in the same order as the supplied keys. If a key is not present in the key-value-store, nil is returned in its place.
196 197 198 199 |
# File 'lib/moneta/adapters/mongo.rb', line 196 def values_at(*keys, **) hash = Hash[slice(*keys, **)] keys.map { |key| hash[key] } end |