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.

config.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.


 <% cache 'signup-text' do %>
   <h1>Welcome to <%= %></h1>
   <p>You have successfully signed up to <%= %>, Your username is:
 <% end %>

     <%= @user.login %>.
     <br />

 <%= render :partial => 'footer' %>


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

  Cache digest for app/views/user_mailer/_footer.erb: 7313427d26cc1f701b1e0212498cee38
  Cache digest for app/views/user_mailer/welcome_email.html.erb: 30efff0173fd5f29a88ffe79a9eab617
  Rendered user_mailer/_footer.erb (0.3ms)
  Rendered user_mailer/welcome_email.html.erb (26.1ms)
  Cache digest for app/views/user_mailer/welcome_email.text.erb: 77f41fe6159c5736ab2026a44bc8de55
  Rendered user_mailer/welcome_email.text.erb (0.2ms)
UserMailer#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.