Class: Moneta::Adapters::MongoDB

Inherits:
Object
  • Object
show all
Includes:
Defaults
Defined in:
lib/moneta/adapters/mongodb.rb

Instance Method Summary collapse

Methods included from Defaults

#[]=, #fetch

Constructor Details

#initialize(options = {}) ⇒ MongoDB

Returns a new instance of MongoDB.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/moneta/adapters/mongodb.rb', line 16

def initialize(options = {})
  collection = options.delete(:collection) || 'cache'

  if uri = options.delete(:uri)
    db_name = URI.parse(uri).path.sub('/','')
    db_name ||= options.delete :db
    conn = Mongo::Connection.from_uri uri, options
  else
    options = {
      :host => ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost',
      :port => ENV['MONGO_RUBY_DRIVER_PORT'] || Mongo::Connection::DEFAULT_PORT,
      :db => 'cache'
    }.update(options)

    host = options.delete :host
    port = options.delete :port
    db_name = options.delete :db

    conn = Mongo::Connection.new(host, port, options)
  end
  db = conn.db db_name
  @cache = db.collection collection
end

Instance Method Details

#[](key) ⇒ Object



44
45
46
47
# File 'lib/moneta/adapters/mongodb.rb', line 44

def [](key)
  res = @cache.find_one('_id' => key_for(key))
  res ? res['data'] : nil
end

#clearObject



64
65
66
# File 'lib/moneta/adapters/mongodb.rb', line 64

def clear(*)
  @cache.remove
end

#delete(key) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/moneta/adapters/mongodb.rb', line 49

def delete(key, *)
  string_key = key_for(key)

  value = self[key]
  @cache.remove('_id' => string_key) if value
  value
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/moneta/adapters/mongodb.rb', line 40

def key?(key, *)
  !!self[key]
end

#store(key, value) ⇒ Object



57
58
59
60
61
62
# File 'lib/moneta/adapters/mongodb.rb', line 57

def store(key, value, *)
  key = key_for(key)
  @cache.update({ '_id' => key },
                { '_id' => key, 'data' => value },
                { :upsert => true })
end