Fastly dynamic caching integration for Rails.
This plugin does three main things:
- Provides instance and class methods on ActiveRecord objects to help with surrogate keys, including purging
- Provides helpers to set Cache-Control and Surrogate-Control response headers
- Provides a controller helper method to set surrogate keys on responses
If you're not familiar with Fastly Surrogate Keys, you might want to check out API Caching and Fastly Surrogate Keys for a primer.
Add to your Gemfile
gem 'fastly-rails'
Create an initializer for Fastly configuration
FastlyRails.configure do |c|
c.api_key = ENV['FASTLY_API_KEY']
c.user = ENV['FASTLY_USER']
c.password = ENV['FASTLY_PASSWORD']
c.max_age = 86400 # time in seconds, optional, defaults to 2592000
c.service_id = ENV['SERVICE_ID'] # whichever Fastly service you will be using
end
Note: purging only requires that you authenticate with your
api_key
.user
andpassword
are added for full compatibility with the Fastly API. Also, you must provide a service_id for purges to work.
Surrogate keys are what Fastly uses to purge groups of individual objects from our caches.
This plugin adds a few methods to generate surrogate keys automatically. table_key
and record_key
methods are added to any ActiveRecord::Base instance. table_key
is also added to any ActiveRecord::Base class. In fact, table_key
on an instance just calls table_key
on the class.
We've chosen a simple surrogate key pattern by default. It is:
table_key: self.class.table_key # calls table_name on the class
record_key: "#{table_key}/#{self.id}"
e.g. If you have an ActiveRecord Model named Book.
table key: books
record key: books/1, books/2, books/3, etc...
You can easily override these methods in your models to use custom surrogate keys that may fit your specific application better:
def self.table_key
"my_custom_table_key"
end
def record_key
"my_custom_record_key" #you should use something unique to each record
end
This plugin adds a set_cache_control_headers
method to ActionController. You'll need to add this in a before_filter
to any controller action that you wish to edge cache (see example below). The method sets Cache-Control and Surrogate-Control header with a default of 30 days (remember you can configure this, see the initializer setup above).
It's up to you to set Surrogate-Key headers for objects that you want to be able to purge.
To do this use the set_surrogate_key_header
method on GET actions.
class BooksController < ApplicationController
# include this before_filter in controller endpoints that you wish to edge cache
before_filter :set_cache_control_headers, only: [:index, :show]
# This can be used with any customer actions. Set these headers for GETs that you want to cache
# e.g. before_filter :set_cache_control_headers, only: [:index, :show, :my_custom_action]
def index
@books = Book.all
set_surrogate_key_header @book.table_key
end
def show
@book = Book.find(params[:id])
set_surrogate_key_header @book.record_key
end
end
Any object that inherits from ActiveRecord will have purge_all
and table_key
class methods available as well as purge
and purge_all
instance methods.
Example usage is show below.
class BooksController < ApplicationController
def create
@book = Book.new(params)
if @book.save
@book.purge_all
render @book
end
end
def update
@book = Book.find(params[:id])
if @book.update(params)
@book.purge
render @book
end
end
def delete
@book = Book.find(params[:id])
if @book.destroy
@book.purge # purge the record
@book.purge_all # purge the collection so the record is no longer there
end
end
end
To simplify controller methods, you could use ActiveRecord callbacks. e.g.
class Book < ActiveRecord
after_create :purge_all
after_save :purge
after_destroy :purge, :purge_all
...
end
We have left these out intentially, as they could potentially cause issues when running locally or testing.
One thing to note is that currently we expect a service_id to be defined in your FastlyRails.configuration. However, we've added localized methods so that your models can override your global service_id, if you needed to operate on more than one for any reason.
Currently, this would require you to basically redefine service_id
on the class level of your model:
class Book < ActiveRecord::Base
def self.service_id
'MYSERVICEID'
end
end
Check out our example todo app which has a full example of fastly-rails integration in a simple rails app.
- Add an option to send purges in batches.
This will cut down on response delay from waiting for large amounts of purges to happen. This would primarily be geared towards write-heavy apps.
- Your feedback
First, install all required gems:
$ appraisal install
This engine is capable of testing against multiple versions of Rails. It uses the appraisal gem. To make this happen, use the appraisal command in lieu of rake test
:
$ appraisal rake test # tests against all the defined versions in the Appraisals file
$ appraisal rails-3 rake test # finds a defined version in the Appraisals file called "rails-3" and only runs tests against this version
We run tests using all combinations of the following versions of Ruby and Rails:
Ruby:
- 1.9.3
- 2.1.1
Rails:
- v3.2.18
- v4.0.5
- v4.1.1
As of v0.1.2, experimental Mongoid support was added by @joshfrench of Upworthy.
This plugin was developed by Fastly with lots of help from our friend at Hotel Tonight, Harlow Ward. Check out his blog about Cache Invalidation with Fastly Surrogate Keys which is where many of the ideas used in this plugin originated.
-- This project rocks and uses MIT-LICENSE.