artsy / garner

A set of Rack middleware and cache helpers that implement various caching strategies.
MIT License
344 stars 24 forks source link

How to cache only anonymous(non-login) request? #87

Closed hey-jude closed 9 years ago

hey-jude commented 9 years ago

I'm using grape for api and devise for authentication. I want to cache api response only if user-request hasn't login info.( Non-login status ). Then, how to do it?

  1. logged-in request serves normal response without caching, don't expires cache data(don't affect with caching).
  2. not-logged-in request serves response with caching
dblock commented 9 years ago

You need to bind with a different key depending on the logged in state. A nice way to accomplish that is to add a different_for_logged_in helper:

module Garner
  module Cache
    class Identity
      def different_for_logged_in(&block)
          key({ logged_in: current_user ? true : false }, &block)
      end
    end
  end
end

You can now do garner.different_for_logged_in do ....

hey-jude commented 9 years ago

@dblock Hmm.. Thank you for your answer, but I don't want different key binding. I want to cache only when not-login state.

hey-jude commented 9 years ago

How about this code?

module Garner
  module Cache
    class Identity
      def only_for_not_logged_in(user, &block)
        if user
          yield
        else
          fetch(&block)
        end
      end
    end
  end
end

And, I'll do garner.only_for_not_logged_in(current_user) do ...

dblock commented 9 years ago

I think that looks reasonable.