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.
source share