Rails 4在Rails.cache.fetch中跳过缓存

Mir*_*age 6 caching ruby-on-rails

我的代码:

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
Run Code Online (Sandbox Code Playgroud)

返回时我不会缓存nil,但确实如此..在这种情况下如何防止缓存?

g8M*_*g8M 1

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

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
Run Code Online (Sandbox Code Playgroud)

如果有人有更好的方法我想知道