Class: Bin::Store

Inherits:
Compatibility show all
Defined in:
lib/bin/store.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection, options = {}) ⇒ Store

Returns a new instance of Store.



6
7
8
# File 'lib/bin/store.rb', line 6

def initialize(collection, options={})
  @collection, @options = collection, options
end

Instance Attribute Details

#collectionObject (readonly)

Returns the value of attribute collection.



4
5
6
# File 'lib/bin/store.rb', line 4

def collection
  @collection
end

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/bin/store.rb', line 4

def options
  @options
end

Instance Method Details

#clearObject



62
63
64
# File 'lib/bin/store.rb', line 62

def clear
  collection.remove
end

#decrement(key, amount = 1) ⇒ Object



56
57
58
59
60
# File 'lib/bin/store.rb', line 56

def decrement(key, amount=1)
  super do
    counter_key_upsert(key, -amount.abs)
  end
end

#delete(key, options = nil) ⇒ Object



32
33
34
35
36
# File 'lib/bin/store.rb', line 32

def delete(key, options=nil)
  super do
    collection.remove(:_id => key)
  end
end

#delete_matched(matcher, options = nil) ⇒ Object



38
39
40
41
42
# File 'lib/bin/store.rb', line 38

def delete_matched(matcher, options=nil)
  super do
    collection.remove(:_id => matcher)
  end
end

#exist?(key, options = nil) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
# File 'lib/bin/store.rb', line 44

def exist?(key, options=nil)
  super do
    !read(key, options).nil?
  end
end

#expires_inObject



10
11
12
# File 'lib/bin/store.rb', line 10

def expires_in
  @expires_in ||= options[:expires_in] || 1.year
end

#increment(key, amount = 1) ⇒ Object



50
51
52
53
54
# File 'lib/bin/store.rb', line 50

def increment(key, amount=1)
  super do
    counter_key_upsert(key, amount)
  end
end

#read(key, options = nil) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/bin/store.rb', line 24

def read(key, options=nil)
  super do
    if doc = collection.find_one(:_id => key, :expires_at => {'$gt' => Time.now.utc})
      doc['raw'] ? doc['value'] : Marshal.load(doc['value'].to_s)
    end
  end
end

#statsObject



66
67
68
# File 'lib/bin/store.rb', line 66

def stats
  collection.stats
end

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



14
15
16
17
18
19
20
21
22
# File 'lib/bin/store.rb', line 14

def write(key, value, options={})
  super do
    expires = Time.now.utc + ((options && options[:expires_in]) || expires_in)
    raw     = !!options[:raw]
    value   = raw ? value : BSON::Binary.new(Marshal.dump(value))
    doc     = {:_id => key, :value => value, :expires_at => expires, :raw => raw}
    collection.save(doc)
  end
end