javascript ruby 80 lines · 3 tabs

Turbo Streams: custom action for flash messages

Shared by codesnips Jan 2026
3 tabs
import { StreamActions } from "@hotwired/turbo"

StreamActions.flash = function () {
  const container = document.getElementById("flashes")
  if (!container) return

  const level = this.getAttribute("level") || "notice"
  const timeout = parseInt(this.getAttribute("timeout") || "5000", 10)

  const toast = document.createElement("div")
  toast.className = `toast toast--${level}`
  toast.setAttribute("role", "status")
  toast.appendChild(this.templateContent)

  const dismiss = document.createElement("button")
  dismiss.className = "toast__close"
  dismiss.textContent = "\u00d7"
  dismiss.addEventListener("click", () => toast.remove())
  toast.appendChild(dismiss)

  container.appendChild(toast)

  if (timeout > 0) {
    setTimeout(() => {
      toast.classList.add("toast--leaving")
      toast.addEventListener("transitionend", () => toast.remove(), { once: true })
    }, timeout)
  }
}
3 files · javascript, ruby Explain with highlit

This snippet shows how to teach Turbo Streams a new verb. Out of the box Turbo ships actions like append, replace, and remove, but nothing that knows how to render a transient flash toast that auto-dismisses. The three files here register a custom flash action on the client, expose a matching helper on the server, and wire it into a controller response so any request can push a notification over the wire.

In flash_stream_action.js, StreamActions.flash is defined by assigning a function onto Turbo's StreamActions registry. When a <turbo-stream action="flash"> element arrives, Turbo invokes this function with the stream element as this, so this.templateContent gives the cloned inner template and this.getAttribute reads custom attributes like level. The handler builds a toast node, appends it to a fixed #flashes container, and schedules removal with setTimeout, giving ephemeral UI without a full Stimulus controller. Registering the action must happen before any stream referencing it is processed, which is why it runs at import time.

TurboFlash helper bridges Ruby and that JavaScript. turbo_stream_flash uses turbo_stream.action, the generic builder that emits a <turbo-stream> tag with an arbitrary action name — here :flash — plus a target and any extra attributes such as level:. This keeps the server ignorant of DOM details; it only names the action and hands over a rendered partial as the template body. Because turbo_stream is already a helper in views and controllers, the method composes cleanly with the standard builder API.

MessagesController demonstrates the payload. On a successful create, respond_to yields a format.turbo_stream block that renders two streams at once: a normal prepend to insert the new message, and turbo_stream_flash to surface a success toast. On validation failure it returns only a flash at the error level with a non-2xx status so Turbo treats it as a form error. The trade-off is a small amount of custom client code in exchange for declarative, reusable notifications that ride along with existing responses, avoiding ad-hoc JSON and manual DOM manipulation. A pitfall to watch is ensuring the #flashes container exists in the layout and that the action name matches exactly on both sides.


Related snips

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
class Post < ApplicationRecord
  belongs_to :author, class_name: 'User'
  has_many :comments, dependent: :destroy

  scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
  scope :draft, -> { where(published_at: nil) }

ActiveRecord scopes for reusable query logic

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
class PostsController < ApplicationController
  def index
    @posts = Post.includes(:author)
                 .order(created_at: :desc)
                 .page(params[:page])
                 .per(10)

Turbo Frames: infinite scroll with lazy-loading frame

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<form data-controller="query-sync" data-action="change->query-sync#apply">
  <select name="status" class="rounded border p-2">
    <option value="">Any</option>
    <option value="open">Open</option>
    <option value="closed">Closed</option>
  </select>

Filter UI that syncs query params via Stimulus (no front-end router)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Turbo Streams: custom action for flash messages — share card
Link copied