DEV Community 👩‍💻👨‍💻

David Paluy
David Paluy

Posted on

slate vs fresh_when - Optimizing Rails Conditional Caching with ETags

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!

Top comments (0)

Make Your Github Profile Stand Out

Github is great, but have you considered how to make yours more attractive for potential employers or other visitors? Even non-tech ones like recruiters!

Take a couple of hours and show your best side as a person - and a programmer.