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.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/moneta/adapters/mongodb.rb', line 14

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

Instance Method Details

#[](key) ⇒ Object



37
38
39
40
# File 'lib/moneta/adapters/mongodb.rb', line 37

def [](key)
  res = @cache.find_one('_id' => key_for(key))
  res && deserialize(res['data'].to_s)
end

#clearObject



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

def clear(*)
  @cache.remove
end

#delete(key) ⇒ Object



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

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)


33
34
35
# File 'lib/moneta/adapters/mongodb.rb', line 33

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

#store(key, value) ⇒ Object



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

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