Skip to content

Instantly share code, notes, and snippets.

@plukevdh
Created April 12, 2011 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save plukevdh/914886 to your computer and use it in GitHub Desktop.
Save plukevdh/914886 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
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
@plukevdh
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment