Skip to content

Instantly share code, notes, and snippets.

@jtushman
Created September 23, 2011 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtushman/1236519 to your computer and use it in GitHub Desktop.
Save jtushman/1236519 to your computer and use it in GitHub Desktop.
Mongo dressed up as Memcached
# My own little Memcache
class KeyValueStore
include Mongoid::Document
include Mongoid::Timestamps::Created
field :key, type: String
field :value, type: Binary
field :expires, type: Time
DEFAULT_EXPIRY = 1.minute
index :key
def self.fetch(key,expires=DEFAULT_EXPIRY)
val = get(key)
if val.nil? && block_given?
val = yield
add(key,val,expires)
end
val
end
def self.get(key)
#TODO can you do find and delete with one op?
entry = where({:key => key,:expires.gt => Time.now}).first
deserialize(entry.value) if entry
end
def self.add(key,val,expires)
expiry_time = Time.now + expires
create({key: key, value: serialize(val), expires_in: expiry_time})
end
def self.flush
where(:expires.lt => Time.now).delete_all
end
private
def self.serialize(val)
BSON::Binary.new(Marshal.dump(val))
end
def self.deserialize(string)
Marshal.load(string)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment