Will nil return from the block passed to Rails.cache.fetch to clear it?

Suppose I have a method like this:

def foo Rails.cache.fetch("cache_key", :expires_in => 60.minutes) do return_something end end 

return_something sometimes returns nil . When this happens, I do not want the nil value to be cached for 60 minutes. Instead, the next time I call foo , I want the block passed to fetch to execute again.

Is Rails.cache.fetch like this by default? Or do I need to implement this functionality?

Update (with answer)

It turns out the answer was negative, at least when using Memcached.

+4
source share
2 answers

it depends on the implementation of your cache storage. I would say that it should not cache nil values, but empty lines in caching order.

look at the implementation of the dalli repository , i.e.:

  def fetch(name, options=nil) options ||= {} name = expanded_key name if block_given? unless options[:force] entry = instrument(:read, name, options) do |payload| payload[:super_operation] = :fetch if payload read_entry(name, options) end end if !entry.nil? instrument(:fetch_hit, name, options) { |payload| } entry else result = instrument(:generate, name, options) do |payload| yield end write(name, result, options) result end else read(name, options) end end 
+2
source

Updated answer to this question: By default, fetch caches nil values, but using the dalli_store mechanism you can avoid it with the cache_nils option:

 Rails.cache.fetch("cache_key", expires_in: 60.minutes, cache_nils: false) do return_something end 
0
source

Source: https://habr.com/ru/post/1439758/


All Articles