Ruby on rails Rails 4跳过Rails.cache.fetch中的缓存

Ruby on rails Rails 4跳过Rails.cache.fetch中的缓存,ruby-on-rails,caching,Ruby On Rails,Caching,我的代码: 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.par

我的代码:

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
当返回
nil
时,我不会缓存,但它会。。
在这种情况下,如何防止缓存?

一种不太优雅的方法是引发错误

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
如果有人有更好的方法,我想知道另一种选择

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