-
-
Save tjsingleton/915701 to your computer and use it in GitHub Desktop.
This file contains 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 | |
class_attribute :namespace | |
class_attribute :redis | |
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.exists key(id) | |
new redis.hgetall(key(id)).to_options | |
end | |
def last_id | |
redis.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.hmset key, *serializable_hash.flatten | |
self | |
end | |
def clear | |
redis.del key | |
end | |
private | |
def incr_key | |
redis.incr key("NEXT_ID") | |
end | |
end | |
RedisObject.redis = REDIS_CONNECTION |
This file contains 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
class TempRedisObject < RedisObject | |
class_attribute :expires_in | |
def persist | |
super.tap do | |
redis.expire key, expires_in | |
end | |
end | |
end | |
TempRedisObject.expires_in = 3.hours.to_i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment