Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get expiration time of Rails cached item

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?

like image 900
blackst0ne Avatar asked Oct 05 '16 08:10

blackst0ne


1 Answers

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.

like image 125
Nick Roz Avatar answered Nov 04 '22 21:11

Nick Roz