Add Varnish cache headers to controller actions. Automatically purge instances and models on after_create
, after_update
and after_destroy
callbacks.
- Add this line to your application's Gemfile:
gem 'varnish_rails'
- Run
$ bundle install
- Install VarnishRails
$ rails generate varnish_rails:install
- Complete the
config/initializers/varnish_rails.rb
file.
-
Add
before_action :set_varnish_headers(max_age_in_seconds)
in controllers that you wanna cache. -
Add calls to
add_to_varnish_xkey_header(my_collection_or_item)
in the cached controller actions to automatically generate the Varnish xkeys. -
For models that don't have to be purged automatically, add the following line
is_updated_via_import
to the model. You can then callMyModel::purge_cache_by_varnish_class_name
to purge all cached pages that use this model. -
You can use Varnish ESI in your layout:
<% if @varnish_headers_are_set %>
<esi:include src="/includes/header"/>
<esi:remove>
<%= render "/shared/header" %>
</esi:remove>
<% else %>
<%= render "/shared/header" %>
<% end %>
- Mario Bouchard
The gem is available as open source under the terms of the MIT License.