DEV Community

David Paluy
David Paluy

Posted on

3 3

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!

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay