Skip to content

Instantly share code, notes, and snippets.

@obahareth
Last active July 1, 2021 15:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save obahareth/c69a4082b4b47e9ccf8f89450c9e8dca to your computer and use it in GitHub Desktop.
Save obahareth/c69a4082b4b47e9ccf8f89450c9e8dca to your computer and use it in GitHub Desktop.
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