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

Walkthrough

Space play step click any line
Three takeaways
  1. 1A small service object keeps broadcasting logic out of the controller and reusable across the app.
  2. 2Turbo Stream broadcasts target a DOM id and render a partial, letting the server drive UI updates over a WebSocket.
  3. 3Streaming per-user means passing the user as the stream identifier so only that person's browser receives the update.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How Turbo Stream toasts broadcast in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code