Class: Moneta::MongoDB

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

Instance Method Summary collapse

Methods included from Defaults

#fetch

Constructor Details

#initialize(options = {}) ⇒ MongoDB

Returns a new instance of MongoDB.



12
13
14
15
16
17
18
19
20
21
# File 'lib/moneta/mongodb.rb', line 12

def initialize(options = {})
  options = {
    :host => ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost',
    :port => ENV['MONGO_RUBY_DRIVER_PORT'] || XGen::Mongo::Driver::Mongo::DEFAULT_PORT,
    :db => 'cache',
    :collection => 'cache'
  }.update(options)
  conn = XGen::Mongo::Driver::Mongo.new(options[:host], options[:port])
  @cache = conn.db(options[:db]).collection(options[:collection])
end

Instance Method Details

#[](key) ⇒ Object



27
28
29
30
31
# File 'lib/moneta/mongodb.rb', line 27

def [](key)
  res = @cache.find_first('_id' => key)
  res = nil if res && res['expires'] && Time.now > res['expires']
  res && res['data']
end

#[]=(key, value) ⇒ Object



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

def []=(key, value)
  store(key, value)
end

#clearObject



53
54
55
# File 'lib/moneta/mongodb.rb', line 53

def clear
  @cache.clear
end

#delete(key) ⇒ Object



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

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

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/moneta/mongodb.rb', line 23

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

#store(key, value, options = {}) ⇒ Object



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

def store(key, value, options = {})
  exp = options[:expires_in] ? (Time.now + options[:expires_in]) : nil
  @cache.repsert({ '_id' => key }, { '_id' => key, 'data' => value, 'expires' => exp })
end

#update_key(key, options = {}) ⇒ Object



48
49
50
51
# File 'lib/moneta/mongodb.rb', line 48

def update_key(key, options = {})
  val = self[key]
  self.store(key, val, options)
end