Last active
July 1, 2021 15:19
-
-
Save obahareth/c69a4082b4b47e9ccf8f89450c9e8dca to your computer and use it in GitHub Desktop.
Supplementary code for this article: https://engineering.mrsool.co/using-redis-hashes-for-caching-in-ruby-on-rails-6dc53df293da
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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