Blog

Thoughts from my daily grind

Rails 5 Improved Collection Caching

Posted by Ziyan Junaideen |Published: 08 March 2016 |Category: Ruby on Rails
Default Upload |

Caching, which is to store and re-use generated content, plays an essential role in delivering fast and responsive web applications. Rails 5 improves upon its predecessors on how we can cache rendered collections.

Previously to cache a collection we would:

// posts/show.html.slim
= render partial: 'posts/_sidebar_post', collection: @featured_posts

// posts/_sidebar_post.html.slim
- cache sidebar_post do
  = sidebar_post.title
  = sidebar_post.views_count

In this setup, the app will be fetching caches for each post. While Redis lookups and fetches are very fast, many fetches are happening here that we can avoid. Nathan Kontny wrote a fascinating gem that addresses precisely this issue. Finally, this feature is now available on Rails 5.

// posts/show.html.slim
= render partial: 'posts/sidebar_post', collection: @featured_posts, cached: true

// posts/_sidebar_post.html.slim
= sidebar_post.title
= sidebar_post.views_count

The new caching setup could speed up renders s in excessive of 75%.

About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments