Skip to content

Instantly share code, notes, and snippets.

@tjsingleton
Forked from plukevdh/redis_object.rb
Created April 12, 2011 15:22
Show Gist options
  • Save tjsingleton/915701 to your computer and use it in GitHub Desktop.
Save tjsingleton/915701 to your computer and use it in GitHub Desktop.
# 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
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