Class: Sprockets::Cache::MongoDBStore

Inherits:
Object
  • Object
show all
Defined in:
lib/sprockets-cache-mongodb/mongodb_store.rb

Overview

A simple MongoDB cache store.

environment.cache = Sprockets::Cache::MongoDBStore.new($mongo)

Instance Method Summary collapse

Constructor Details

#initialize(mongo_conn, db_name = 'sprockets') ⇒ MongoDBStore

Returns a new instance of MongoDBStore.



9
10
11
# File 'lib/sprockets-cache-mongodb/mongodb_store.rb', line 9

def initialize(mongo_conn, db_name = 'sprockets')
  @mongo = ::Mongo::Grid.new( mongo_conn.db(db_name) )
end

Instance Method Details

#[](key) ⇒ Object

Lookup value in cache



14
15
16
17
18
19
20
# File 'lib/sprockets-cache-mongodb/mongodb_store.rb', line 14

def [](key)
  sanitized_key = sanitize_key(key)
  return unless @mongo.exist?(:filename => sanitized_key)
  object = @mongo.get sanitized_key
  data   = object.read
  Marshal.load data if data
end

#[]=(key, value) ⇒ Object

Save value to cache



23
24
25
26
27
28
29
# File 'lib/sprockets-cache-mongodb/mongodb_store.rb', line 23

def []=(key, value)
  @mongo.put  Marshal.dump(value),
              :_id          => sanitize_key(key),
              :filename     => sanitize_key(key),
              :content_type => "application/x-ruby-marshal"
  value
end