My code:
def my_method(path)
Rails.cache.fetch(path, expires_in: 10.minutes, race_condition_ttl: 10) do
# Calls Net::HTTP.get_response URI.parse path
response = My::api.get path
if response.status == 200
JSON.parse response.body
else
nil # Here I need to prevent cache
end
end
end
I won't cache when return nil
, but it does..
How do I prevent caching in this case?
One not so elegant way is raising erros.
def my_method(path)
Rails.cache.fetch(path, expires_in: 10.minutes, race_condition_ttl: 10) do
# Calls Net::HTTP.get_response URI.parse path
response = My::api.get path
raise MyCachePreventingError unless response.status == 200
JSON.parse response.body
end
rescue MyCachePreventingError
nil
end
If someone has some better way I'd like to know
Another alternative...
def my_method(path)
out = Rails.cache.fetch(path, expires_in: 10.minutes, race_condition_ttl: 10) do
# Calls Net::HTTP.get_response URI.parse path
response = My::api.get path
if response.status == 200
JSON.parse response.body
else
nil # Here I need to prevent cache
end
end
Rails.cache.delete(path) if out.nil?
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With