Rails Caching: Expiring Multiple Pages for a Single Action

I set up action caching (with sweepers, but I think it doesn’t matter here) in my application and it still works fine except for one:

I use Kaminari for pagination, and so when I execute expire_action on my action, it ends only on the first page. Since I know that caching will not work when using a query string to specify a page, I set the route so that the pages are added to the end of the URL (e.g. / people / 123 / page / 2).

I will add additional information to this post if necessary, but I assume that there is something obvious that I am not here, so: Does anyone know how the rest of my pages expired?

+6
source share
2 answers

I am still interested in the answer to my original question and will change my accepted answer if a solution arrives. However, I ended up only caching the original page, checking if the page was specified at all:

caches_action: index ,: if => Proc.new {params [: page] .nil? }

+5
source

Here is the solution I was thinking about when I came across the same problem, although I have not yet implemented it. Cache the actual expiration time in your own key. The key will be the canonical representation of the search URL, that is, without the page parameter. eg:.

The user searches on http://example.com?q=foo&page=3 , so the parameters are { q: 'foo', page: 3 } . Cut "page = 3" and we are left with {q: 'foo'}.

Run to_param and add some prefix, and we will have the key cache, for example search_expiry_q=foo .

Browse the cache for this canonical query, i.e. Rails.cache.read ( search_expiry_q=foo ). If it exists, we will make our result expire at this time. Unfortunately, we only have expires_in , not expires_at , so we have to do the calculation. that is, something like expires_in: expiry_time - Time.now - 5.seconds (5 seconds, I hope, prevent any race conditions). Thus, we cache the full URL / params.

OTOH, if there is no expiration, then no one has searched recently. So:

 expiry_time = Time.now + 1.hour Rails.cache.write(`search_expiry_q=foo`, expiry_time, expires_in: 1.hour) 

And cache this snippet / page, again with full URL / params and expires_in: 1.hour.

+1
source

Source: https://habr.com/ru/post/916158/


All Articles