Why does using "return" in Rails.cache.fetch block fail to cache?

Viewed 667

Why does using return in Rails.cache.fetch cause a cache miss?

# doesn't catch
Rails.cache.fetch("key", expires_in: 12.hours) do
 puts "CACHE MISS" 
 return "HI"
end

# caches
Rails.cache.fetch("key", expires_in: 12.hours) do 
 puts "CACHE MISS"
 "HI"
end
1 Answers

To provide an explanation for this, we first need to understand how yield works:

  • The yield keyword allows passing a set of additional instructions during a method invocation. Meaning, that a method can accept a block (besides the regular arguments) and execute that block from inside the method by using the yield keyword.

  • Another thing we need to know is that when executing a yield block, if calling return in it, it returns the whole method and not just the block.

  • See further information on yield here.

The Rails.cache.fetch method is implemented by accepting a block and executing it using the yield keyword (with some additional logic). Hence, When returning from inside the block that is sent to Rails.cache.fetch, the whole method is returned without first processing (caching) the block yielding results, and the caching fails.

Related