public
Created

  • Download Gist
redis_object.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
# 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

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.