Somewhere in my app I use
Rails.cache.write 'some_key', 'some_value', expires_in: 1.week
In another part of my app I want to figure out how much time it is left for that cache item.
How do I do that?
This is not a legal way, but it works:
expires_at = Rails.cache.send(:read_entry, 'my_key', {})&.expires_at
expires_at - Time.now.to_f if expires_at
read_entry
is protected method that is used by fetch, read, exists? and other methods under the hood, that's why we use send
.
It may return nil
if there is no entry at all, so use try
with Rails, or &.
for safe navigation, or .tap{ |e| e.expires_at unless e.nil? }
for old rubies.
As a result you will get something like 1587122943.7092931
. That's why you need Time.now.to_f
. With Rails you can use Time.current.to_f
as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With