Class: Moneta::Adapters::MongoOfficial
- 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.
Constant Summary
Constants inherited from MongoBase
Moneta::Adapters::MongoBase::DEFAULT_PORT
Instance Attribute Summary
Attributes inherited from MongoBase
Attributes included from ExpiresSupport
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.
-
#increment(key, amount = 1, options = {}) ⇒ Object
Atomically increment integer value with key.
-
#initialize(options = {}) ⇒ MongoOfficial
constructor
A new instance of MongoOfficial.
-
#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.
Methods inherited from MongoBase
Methods included from Defaults
#[], #[]=, #decrement, #features, #fetch, #fetch_values, included, #key?, #supports?, #update, #values_at
Methods included from OptionSupport
#expires, #prefix, #raw, #with
Constructor Details
#initialize(options = {}) ⇒ MongoOfficial
Returns a new instance of MongoOfficial.
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( = {}) super() collection = .delete(:collection) || 'moneta' db = .delete(:db) || 'moneta' @backend = [:backend] || begin host = .delete(:host) || '127.0.0.1' port = .delete(:port) || DEFAULT_PORT [:logger] ||= ::Logger.new(STDERR).tap do |logger| logger.level = ::Logger::ERROR end ::Mongo::Client.new(["#{host}:#{port}"], ) end @backend.use(db) @collection = @backend[collection] if @backend.command(buildinfo: 1).documents.first['version'] >= '2.2' @collection.indexes.create_one({@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
112 113 114 115 |
# File 'lib/moneta/adapters/mongo/official.rb', line 112 def clear( = {}) @collection.delete_many self end |
#close ⇒ Object
Explicitly close the store
118 119 120 121 |
# File 'lib/moneta/adapters/mongo/official.rb', line 118 def close @backend.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.
102 103 104 105 106 107 108 109 |
# File 'lib/moneta/adapters/mongo/official.rb', line 102 def create(key, value, = {}) key = to_binary(key) @collection.insert_one(value_to_doc(key, value, )) true rescue ::Mongo::Error::OperationFailure => ex raise unless ex. =~ /^E11000 / # duplicate key error false end |
#delete(key, options = {}) ⇒ Object
Delete the key from the store and return the current value
84 85 86 87 88 89 90 91 |
# File 'lib/moneta/adapters/mongo/official.rb', line 84 def delete(key, = {}) key = to_binary(key) if doc = @collection.find(_id: key).find_one_and_delete and !doc[@expires_field] || doc[@expires_field] >= Time.now then 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.
77 78 79 80 81 |
# File 'lib/moneta/adapters/mongo/official.rb', line 77 def each_key return enum_for(:each_key) unless block_given? @collection.find.each { |doc| yield from_binary(doc[:_id]) } self 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.
94 95 96 97 98 99 |
# File 'lib/moneta/adapters/mongo/official.rb', line 94 def increment(key, amount = 1, = {}) @collection.find_one_and_update({ _id: to_binary(key) }, { '$inc' => { @value_field => amount } }, :return_document => :after, :upsert => true)[@value_field] end |
#load(key, options = {}) ⇒ Object
Fetch value with key. Return nil if the key doesn't exist
55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/moneta/adapters/mongo/official.rb', line 55 def load(key, = {}) key = to_binary(key) doc = @collection.find(_id: key).limit(1).first if doc && (!doc[@expires_field] || doc[@expires_field] >= Time.now) expires = expires_at(, nil) # @expires_field must be a Time object (BSON date datatype) @collection.update_one({ _id: key }, '$set' => { @expires_field => expires }) unless expires.nil? 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.
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
# File 'lib/moneta/adapters/mongo/official.rb', line 139 def merge!(pairs, = {}) existing = Hash[slice(*pairs.map { |key, _| key })] update_pairs, insert_pairs = pairs.partition { |key, _| existing.key?(key) } @collection.insert_many(insert_pairs.map do |key, value| value_to_doc(to_binary(key), value, ) 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 Moneta::Adapters::MongoBase#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.
124 125 126 127 128 129 130 131 132 133 134 135 136 |
# File 'lib/moneta/adapters/mongo/official.rb', line 124 def slice(*keys, **) query = @collection.find(_id: {:$in => keys.map(&method(:to_binary))}) pairs = query.map do |doc| next if doc[@expires_field] && doc[@expires_field] < Time.now [from_binary(doc[:_id]), doc_to_value(doc)] end.compact if (expires = expires_at(, nil)) != nil query.update_many(:$set => { @expires_field => expires || nil }) end pairs end |
#store(key, value, options = {}) ⇒ Object
Store value with key
68 69 70 71 72 73 74 |
# File 'lib/moneta/adapters/mongo/official.rb', line 68 def store(key, value, = {}) key = to_binary(key) @collection.replace_one({ _id: key }, value_to_doc(key, value, ), upsert: true) value end |