Caching means to store content generated during a request/response cycle and re-use the content when serving the same request.
Types of Rails Caching
- Page caching
- Action caching
- Fragment caching
As page caching and Action caching has been removed from Rails 4, lets discuss about fragment caching here.
Generally, a web application will use multiple components to build a web page (eg: ruby , JS, jQuery etc..,). Each component will use different cache mechanisms. Fragment caching allows to cache a particular view block and serve the copy when requested.
In view file article.html.erb
On the first request to this page, Rails will cache this fragment. The cache entry will look something like views/articles/1-201505056193031061005000/bea67108094918eeba42cd4a6e786901
cache entry understanding:
/1-201505056193031061005000 – The middle part has two break ups. The article_id and updated_at attribute from the article object. The updated_at attribute is used to check if the cached object has changed. if it is not changed, then
bea67108094918eeba42cd4a6e786901 – This is a HTML template tree hash (a MD5 hash). This is to determine if the cached HTML has changed. Even when the HTML has changed, the caching will become invalid. This will change when the HTML template change and thus this will expire the old cache.
If the caching has to be done in a condition, we can use either cache_if / cache_unless.
Russian Doll Caching:
Nesting of a cached fragment inside another cached fragment is called Russian Doll Caching.
Which in turn has a cached fragment authors/show.html.erb
So, whenever there is a change in the author object, the updated_at of the author object will be updated. This will expire the caching of author template. But as the article’s updated_at is not changed, the articles/index.html.erb will be served from the cache and still has the old data.
To overcome this issue, we should set touch :true in the author model.
By adding touch, any change in author’s updated_at will also expire article’s cache.
To Be Continued…