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

时间:2014-08-26 05:23:48

标签: 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.parse response.body
        else
            nil # Here I need to prevent cache
        end
    end
end

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

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:1)

另一种选择......

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