mahemoff
mahemoff

Reputation: 46479

Rails: Conditionally bypass fragment caching

Is there any way to make fragment caching conditional, e.g. this will always cache:

 <% cache :calculation do %>
   <%= calc(x) %>
 <% end %>

But how could I make it cache if e.g. x > 5, something like:

 <% cache :calculation, { if: (x > 5) } do %>
   <%= calc(x) %>
 <% end %>

Of course, it could be done with an if-then statement and extracting out the cached content function, but that's messy. Possibly it could work by setting ttl to zero on this condition, but I suspect that would still put the item in the cache, which is wasted space.

Upvotes: 0

Views: 240

Answers (1)

dnsh
dnsh

Reputation: 3633

Have you tried cache_if

<% cache_if((x > 5), :calculation) do %>
  <%= calc(x) %>
<% end %>

Upvotes: 2

Related Questions