Skip to content
This repository has been archived by the owner on Dec 13, 2023. It is now read-only.

fastly/fastly-rails

Repository files navigation

Fastly Rails Plugin Build Status

Deprecation Notice

This repository has been deprecated. The official Fastly Ruby client is the fastly-ruby gem.

Although this repository is no longer supported, it could be useful as a reference.


Introduction

Fastly dynamic caching integration for Rails.

To use Fastly dynamic caching, you tag any response you wish to cache with unique Surrogate-Key HTTP Header(s) and then hit the Fastly API purge endpoint with the surrogate key when the response changes. The purge instantly replaces the cached response with a fresh response from origin.

This plugin provides three main things:

  • Instance and class methods on ActiveRecord (or Mongoid) objects for surrogate keys and purging
  • Controller helpers to set Cache-Control and Surrogate-Control response headers
  • A controller helper to set Surrogate-Key headers 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.

Setup

Add to your Gemfile

gem 'fastly-rails'

Configuration

For information about how to find your Fastly API Key or a Fastly Service ID, refer to our documentation.

Create an initializer for Fastly configuration

FastlyRails.configure do |c|
  c.api_key = ENV['FASTLY_API_KEY']  # Fastly api key, required
  c.max_age = 86400                  # time in seconds, optional, defaults to 2592000 (30 days)
  c.stale_while_revalidate = 86400   # time in seconds, optional, defaults to nil
  c.stale_if_error = 86400           # time in seconds, optional, defaults to nil
  c.service_id = ENV['SERVICE_ID']   # The Fastly service you will be using, required
  c.purging_enabled = !Rails.env.development? # No need to configure a client locally (AVAILABLE ONLY AS OF 0.4.0)
end

Note: purging only requires that you authenticate with your api_key. However, you can provide a user and password if you are using other endpoints in fastly-ruby that require full-auth. Also, you must provide a service_id for purges to work.

Usage

Surrogate Keys

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"# Ensure these are unique for each record
end

Headers

This plugin adds a set_cache_control_headers method to ActionController. You'll need to add this in a before_filter or after_filter see note on cookies below to any controller action that you wish to edge cache (see example below). The method sets Cache-Control and Surrogate-Control HTTP Headers 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 'books', @books.map(&:record_key)
  end

  def show
    @book = Book.find(params[:id])
    set_surrogate_key_header @book.record_key
  end
end

Purges

Any object that inherits from ActiveRecord will have purge_all, soft_purge_all, and table_key class methods available as well as purge, soft_purge, purge_all, and soft_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