slate vs fresh_when - Optimizing Rails Conditional Caching with ETags

David Paluy - Aug 22 '20 - - Dev Community

Conditional Caching is usually something that many developers forget while deploying to production.

In this post, I will refresh your memory by summarizing those options and improving your application performance.

Setting etag or/and last_modified in the response

The request will return 304 status code if nothing changed.

fresh_when example

class ArticleController < ApplicationController
  def show
    @article = Article.find(params[:id])
  fresh_when(etag: @article, last_modified: @article.updated_at)
  end
end
Enter fullscreen mode Exit fullscreen mode

Note: check the fresh_when documentation for all possible options.

Checking etag and last_modified against the client request with slate?

class ArticleController < ApplicationController
  def show
    @article = Article.find(params[:id])

    if stale?(@article)
      @statistics = @article.statistics # very long task
      respond_to do |format|
        format.html # show.html.erb    
      end
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Note: slate API

slate? is similar to fresh_when but adds an additional helper to make responses efficiently.

My rule: If you have special response processing, use slate? helper. Otherwise, fresh_when is your default choice.

Happy Hacking!

. . . . . . . . . . . . .
Terabox Video Player