Hello Rails community,
I’m using the low-level cache functions available in Rails to store data on a memcache server to make some background jobs faster. In detail I’m using (spanned in different jobs with the same key):
Rails.cache.read(key) # read data from cache (if exists)
...
Rails.cache.write(key, value) # to update/insert data that is/isn't already written on cache
...
Rails.cache.delete(key) # delete data from cache
I can ensure that the write
really writes data on the cache by checking the return value, if it’s true I know that data has been written on the cache, if nil or false some error occurred so the value on the cache has not being updated, in my case I’ll raise an exception and the job restarts.
With the delete
method I can’t understand if the delete has been done or not because it returns false in both case:
- key not found
- some error connecting to the store
So I’ve rewritten the deletes as writes:
# By setting the value to nil with zero expiration time, we ensure that:
# - Any subsequent read will return nil, effectively simulating a delete.
# - Cache coherency is maintained in distributed environments.
# - Future fetch operations will treat this as a cache miss and execute their blocks.
Rails.cache.write(key, nil, expires_in: 0.seconds)
And by checking the return value I can understand if the key has been removed or not.
I understand that I’m using the cache in a non-standard way, and I think that with my usage is better to directly set up and use a key/value database, at the same time everything is already in place to use the functions already available .
So, I’m wondering if adding something like a write!
or a delete!
method to Rails Cache that raises an exception if the data has not been written on the cache makes sense or not. What do you think?
Thank you
Nicola