Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 741
Miraage Avatar asked Aug 26 '14 05:08

Miraage


2 Answers

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

like image 54
g8M Avatar answered Sep 22 '22 17:09

g8M


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
like image 35
montrealmike Avatar answered Sep 25 '22 17:09

montrealmike