如何知道日期过期和创建日期的缓存文件在rails?



我使用Ruby3+和Rails 6+和缓存文件:config.cache_store = :file_store, 'public/cache'

I try:

key = 'test'
Rails.cache.write(key, 'test!!')

缓存文件工作正常:

Rails.cache.read(key)
=> "test!!"

但如果我尝试在其他帖子上找到的解决方案,就像这样:

Rails.cache.send(:read_entry, key, {}).expires_at

我有以下错误:

/home/USER/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/cache/strategy/local_cache.rb:131:in `read_entry': wrong number of arguments (given 2, expected 1) (ArgumentError)

如果我尝试删除最后一个参数{},没有错误,但返回nil…

那么我如何找到我的缓存的过期和创建日期?

如果你想知道一个缓存项是什么时候创建的,你可以使用这个方法。

您可以将创建日期与您的数据一起写入

key = "some key"
Rails.cache.write(key, { expires_at: Time.current + 1.day, value: "test!!!" })`

然后用

检索
item = Rails.cache.read(key)
item[:value] 
# => test!!!
item[:expires_at]
# => 20211023********

您可以轻松地将其转换为一些实用程序帮助器方法,以使您的工作更轻松。

# In some helper or utility class
def write_to_cache(key, value, expiry_time = 1.day)
Rails.cache.write(key, { expires_at: Time.current + expiry_time, value: value })
end
def cache_key_value(key)
item = Rails.cache.read("key")
item[:value]
end
def cache_key_expires_at(key)
item = Rails.cache.read("key")
item[:expires_at]
end
# somewhere else
key = "test"
write_to_cache(key, "test value")
cache_key_value(key)
# => "test value"
cache_key_expires_at(key)
# => 20211023********