ruby
32 lines · 6 steps
How Turbo Stream toasts broadcast in Rails
A service object pushes flash toast messages to a user's browser over Turbo Streams without a full page reload.
Explained by
highlit
1class ToastBroadcaster
2 include ActionView::RecordIdentifier
3
4 def self.broadcast_to(user, message:, type: :notice)
5 new(user).broadcast(message: message, type: type)
6 end
7
8 def initialize(user)
9 @user = user
10 end
11
12 def broadcast(message:, type:)
13 Turbo::StreamsChannel.broadcast_prepend_to(
14 @user,
15 target: "toasts",
16 partial: "shared/toast",
17 locals: { toast_id: SecureRandom.uuid, message: message, type: type }
18 )
19 end
20end
21
22class FlashToastsController < ApplicationController
23 def create
24 ToastBroadcaster.broadcast_to(
25 current_user,
26 message: params.require(:message),
27 type: params.fetch(:type, :notice)
28 )
29
30 head :no_content
31 end
32end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A small service object keeps broadcasting logic out of the controller and reusable across the app.
- 2Turbo Stream broadcasts target a DOM id and render a partial, letting the server drive UI updates over a WebSocket.
- 3Streaming per-user means passing the user as the stream identifier so only that person's browser receives the update.
Related explainers
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
php
<?php namespace App\Broadcasting;
Authorizing presence channels in Laravel
broadcasting
authorization
presence-channels
Intermediate
3 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 steps
ruby
class Order < ApplicationRecord include AASM belongs_to :warehouse
Modeling an order lifecycle with AASM in Rails
state machine
guards
callbacks
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-turbo-stream-toasts-broadcast-in-rails-explained-ruby-bc76/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.