Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 fragment caching with stylesheet_link_tag

Rails 4 uses cache_digests (https://github.com/rails/cache_digests) to assist with fragment cache invalidation: cache_digests creates an MD5 hash of a template and all its known dependencies, allowing fragment caches to become invalidated by assigning a new key when a template or its dependency changes.

My question is: will a fragment cache wrapping stylesheet_link_tag get invalidated if the application.css file's MD5 hash changes during rake assets:precompile? Right now do this in our header:

<% cache("header-cache-key") do %>
  <%= stylesheet_link_tag "application" %>
  <%= javascript_include_tag "application" %>
<% end %>

Is this safe? My fear is that when the CSS or JS changes, application-xxxxxxx.css will become application-yyyyyyy.css, but our header will be cached with the old application-xxxxxxx.css. Then if application-xxxxxxx.css is gone from public/assets, this will result in an ugly page.

like image 342
oregontrail256 Avatar asked Nov 05 '14 02:11

oregontrail256


1 Answers

No the cache wont be busted/invalidated on changes to compiled CSS/JS.

The way Rails busts the cache on a code change is done by inserting a file's hash into the view's cache key.

E.g say you have a view file at app/views/layouts/application.html.erb. Rails generates a hash from the file's content (i.e the HTML/Ruby code, not the executed output). Let's pretend the hash generated is 'abdefg123'.

If application.html.erb has the following cache code:

<% cache("header-cache-key") do %>
  <%= stylesheet_link_tag "application" %>
  <%= javascript_include_tag "application" %>
<% end %>

The actual cache key generated is something along the of lines "views/layouts/application-abcdefg123/header-cache-key".

As a change in the compiled CSS/JS doesn't actually change the Ruby/HTML in the file, the computed hash for the layout code doesn't change and therefore the cache key for 'header-cache-key' is the same, meaning the cache isn't busted.

like image 71
Pete Avatar answered Sep 19 '22 23:09

Pete