Rails 5 provides fragment caching in Action Mailer views

Prajakta Tambe

By Prajakta Tambe

on May 31, 2016

This blog is part of our  Rails 5 series.

Fragment cache helps in caching parts of the view instead of caching the entire view. Fragment caching is used when different parts of the view need to be cached and expired separately. Before Rails 5, fragment caching was supported only in Action View templates.

Rails 5 provides fragment caching in Action Mailer views . To use this feature, we need to configure our application as follows.

1config.action_mailer.perform_caching = true

This configuration specifies whether mailer templates should perform fragment caching or not. By default, this is set to false for all environments.

Fragment caching in views

We can do caching in mailer views similar to application views using cache method. Following example shows usage of fragment caching in mailer view of the welcome mail.

3 <% cache 'signup-text' do %>
4   <h1>Welcome to <%= @company.name %></h1>
5   <p>You have successfully signed up to <%= @company.name %>, Your username is:
6 <% end %>
8     <%= @user.login %>.
9     <br />
10   </p>
12 <%= render :partial => 'footer' %>

When we render view for the first time, we can see cache digest of the view and its partial.

1  Cache digest for app/views/user_mailer/_footer.erb: 7313427d26cc1f701b1e0212498cee38
2  Cache digest for app/views/user_mailer/welcome_email.html.erb: 30efff0173fd5f29a88ffe79a9eab617
3  Rendered user_mailer/_footer.erb (0.3ms)
4  Rendered user_mailer/welcome_email.html.erb (26.1ms)
5  Cache digest for app/views/user_mailer/welcome_email.text.erb: 77f41fe6159c5736ab2026a44bc8de55
6  Rendered user_mailer/welcome_email.text.erb (0.2ms)
7UserMailer#welcome_email: processed outbound mail in 190.3ms

We can also use fragment caching in partials of the action mailer views with cache method. Fragment caching is also supported in multipart emails.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.