Get expiration time of Rails cached item

半城伤御伤魂 提交于 2020-05-13 02:34:54

问题


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?


回答1:


Wow. I just came here looking for this. What a shame the answer is no.

My solution, then, which I'm not a fan of, is to cache the expiration as well.

Rails.cache.write 'some_key', ['some_value', 1.week.from_now], expires_in: 1.week

I suppose it's not the end of the world, except that you have to remember it was stored as an array.

Alternatively you could abstract the functionality a little with a cacheable module. Then you don't have to "remember" anything.




回答2:


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.



来源:https://stackoverflow.com/questions/39868775/get-expiration-time-of-rails-cached-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!