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)
}
}
module TurboFlash
def turbo_stream_flash(message, level: :notice, target: "flashes", timeout: 5000)
turbo_stream.action(
:flash,
target,
level: level,
timeout: timeout
) { content_tag(:p, message, class: "toast__body") }
end
end
ActiveSupport.on_load(:action_controller) do
helper TurboFlash
include TurboFlash
end
ActiveSupport.on_load(:action_view) do
include TurboFlash
end
class MessagesController < ApplicationController
def create
@message = current_conversation.messages.build(message_params)
@message.author = current_user
respond_to do |format|
if @message.save
format.turbo_stream do
render turbo_stream: [
turbo_stream.prepend("messages", partial: "messages/message", locals: { message: @message }),
turbo_stream_flash("Message sent.", level: :success)
]
end
format.html { redirect_to current_conversation }
else
format.turbo_stream do
render turbo_stream: turbo_stream_flash(
@message.errors.full_messages.to_sentence,
level: :error,
timeout: 8000
), status: :unprocessable_entity
end
end
end
end
private
def message_params
params.require(:message).permit(:body)
end
end
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
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
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
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
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
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
<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)
Share this code
Here's the card — post it anywhere.