Class: ActiveSupport::Cache::MongoStore

Inherits:
Store
  • Object
show all
Includes:
MongoStore::Cache::Store
Defined in:
lib/active_support/cache/mongo_store.rb

Instance Method Summary collapse

Methods included from MongoStore::Cache::Store

#expires_in, #expires_in=

Constructor Details

#initialize(collection = nil, options = nil) ⇒ MongoStore

Returns a MongoDB cache store. Can take either a Mongo::Collection object or a collection name. If neither is provided, a collection named “rails_cache” is created.

An options hash may also be provided with the following options:

  • :expires_in - The default expiration period for cached objects. If not provided, defaults to 1 day.

  • :db - Either a Mongo::DB object or a database name. Not used if a Mongo::Collection object is passed. Otherwise defaults to MongoMapper.database (if MongoMapper is used in the app) or else creates a DB named “rails_cache”.

  • :create_index - Whether to index the key and expiration date on the collection. Defaults to true. Not used if a Mongo::Collection object is passed.



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/active_support/cache/mongo_store.rb', line 127

def initialize(collection = nil, options = nil)
  @options = {
    :collection_name => 'rails_cache',
    :db_name => 'rails_cache',
    :expires_in => 86400,  # That's 1 day in seconds
    :create_index => true
  }
  # @options.merge!(options) if options
  case collection
  when Mongo::Collection
    @collection = collection
  when String
    @options[:collection_name] = collection
  when Hash
    @options.merge!(collection)
  when nil
    # No op
  else
    raise TypeError, "MongoStore parameters must be a Mongo::Collection, a collection name, and/or an options hash."
  end
  
  @options.merge!(options) if options.is_a?(Hash)
end

Instance Method Details

#clean_expiredObject

Removes old cached values that have expired. Set this up to run occasionally in delayed_job, etc., if you start worrying about space. (In practice, because we favor updating over inserting, space is only wasted if the key itself never gets cached again. It also means you can reduce efficiency by running this too often.)



162
163
164
# File 'lib/active_support/cache/mongo_store.rb', line 162

def clean_expired
  collection.remove({'expires' => {'$lt' => Time.now}})
end

#clearObject

Wipes the whole cache.



167
168
169
# File 'lib/active_support/cache/mongo_store.rb', line 167

def clear
  collection.remove
end

#collectionObject

Returns the MongoDB collection described in the options to .new (or else the default ‘rails_cache’ one.) Lazily creates the object on first access so that we can look for a MongoMapper database after MongoMapper initializes.



154
155
156
# File 'lib/active_support/cache/mongo_store.rb', line 154

def collection
  @collection ||= make_collection
end