Created
April 12, 2011 03:56
-
-
Save plukevdh/914886 to your computer and use it in GitHub Desktop.
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
# super-meta object persistence class to Redis | |
class RedisObject | |
include ActiveModel::Serialization | |
attr_accessor :attributes, :id | |
cattr_writer :namespace | |
class << self | |
def namespace | |
@namespace || self | |
end | |
def key(id) | |
"#{namespace}:%s" % id | |
end | |
# specifically use the generic initializer to rebuild object | |
def find(id) | |
return nil unless REDIS_CONNECTION.exists key(id) | |
new REDIS_CONNECTION.hgetall(key(id)).to_options | |
end | |
def last_id | |
REDIS_CONNECTION.get key("NEXT_ID") | |
end | |
def last | |
find last_id | |
end | |
end | |
def initialize(params = {}) | |
@attributes = params | |
@id = params[:id] || nil | |
end | |
def read_attribute_for_validation(key) | |
@attributes[key] | |
end | |
alias :[] :read_attribute_for_validation | |
def key(id=@id) | |
self.class.key(id) | |
end | |
# store in redis | |
def persist | |
@attributes[:id] = @id = incr_key | |
REDIS_CONNECTION.hmset key, *serializable_hash.flatten | |
REDIS_CONNECTION.expire key, 3.hours.to_i | |
self | |
end | |
def clear | |
REDIS_CONNECTION.del key | |
end | |
private | |
def incr_key | |
REDIS_CONNECTION.incr key("NEXT_ID") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, this is a temporary persistence. For our current usage, this object get discarded rather quickly as we use it to simplify passing data around in requests. But it doesn't have to be that way. Just remove the
REDIS_CONNECTION.expire key, 3.hours.to_i