Miraage
Miraage

Reputation: 3464

Rails 4 skip cache in Rails.cache.fetch

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?

Upvotes: 6

Views: 1907

Answers (2)

montrealmike
montrealmike

Reputation: 11641

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

Upvotes: 1

g8M
g8M

Reputation: 1263

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

Upvotes: 1

Related Questions