Condition to skip ActiveSupport::Cache::Store#fetch save

Nowadays when we use the method cache.fetch has an option for skipping the result store skip_nil where it does not store the result value if it’s nil…

However, there are some cases where the block result is not nil and we don’t want to store the result. Is it possible, we have an option, for example, skip_if where we can specify a condition to skip the cache storing like the skip_nil does?

Expected behavior

failed_request = ->(response) { !response.is_a?(Net::HTTPOK) }

response  = cache.fetch('search', skip_if: failed_request ) do 
  Net::HTTP.get_response(URI('https://www.google.com'))
end

# When response is Net::HTTPOK
cache.exist?('search') # => true

# When response is not Net::HTTPOK
cache.exist?('search') # => false

It could be almost reached using skip_nil,

response = cache.fetch('foo', skip_nil: true) do
  resp = Net::HTTP.get_response(URI('https://www.google.com'))

  resp.is_a?(Net::HTTPOK) ? resp: nil
end

However, it does not allow to get the response out of the block, because it changes to nil.

I’m not aware of this feature, but you could try using a raise inside the fetch, and rescuing it outside. This should be enough to prevent the write while allowing you to continue as normal. Since your example is about a network failure, it’s not something that will happen enough that the performance penalty of raising would matter.