Created
September 23, 2011 01:10
-
-
Save jtushman/1236519 to your computer and use it in GitHub Desktop.
Mongo dressed up as Memcached
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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