---
title: "Rails 5 provides fragment caching in Action Mailer views"
description:
  "Templates in rails 5 can use fragment cache like Action View templates"
canonical_url: "https://www.bigbinary.com/blog/rails-5-provides-fragment-caching-in-action-mailer-view"
markdown_url: "https://www.bigbinary.com/blog/rails-5-provides-fragment-caching-in-action-mailer-view.md"
---

# Rails 5 provides fragment caching in Action Mailer views

Templates in rails 5 can use fragment cache like Action View templates

- Author: Prajakta Tambe
- Published: May 31, 2016
- Categories: Rails 5, Rails

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](https://github.com/rails/rails/commit/e40518f5d44303ed91641b342a53bdfb32753de3)
. To use this feature, we need to configure our application as follows.

```ruby
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.

```ruby
<body>

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

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

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

</body>
```

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

```ruby
  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.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-5-provides-fragment-caching-in-action-mailer-view)
