Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
module RedisHashStore
extend self
class Entry
attr_reader :value
def initialize(value, expires_in:)
@value = value
@created_at = Time.now.to_f
@expires_in = expires_in
end
def expired?
@expires_in && @created_at + @expires_in <= Time.now.to_f
end
end
def write(hash_key, sub_key, value, **options)
entry = Entry.new(value, expires_in: options[:expires_in])
redis.hset(hash_key, sub_key, serialize_value(entry))
entry.value
end
def read(hash_key, sub_key)
entry = deserialize_value(redis.hget(hash_key, sub_key))
return if entry.blank?
if entry.expired?
delete(hash_key, sub_key)
return nil
end
entry.value
end
def delete(hash_key, sub_key)
redis.hdel(hash_key, sub_key)
end
def delete_hash(hash_key)
redis.del(hash_key)
end
private
def serialize_value(value)
Marshal.dump(value)
end
def deserialize_value(value)
return if value.nil?
Marshal.load(value)
end
def redis
Rails.cache.redis
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment