Conditionally showing/hiding Turbo Stream broadcasts
15 June 2021
The turbo-rails library allows us to broadcast Turbo Stream updates over websockets.
This means we can push real-time page updates to many users at once.
But what if we want to conditionally show or hide updates, depending on
Example of the problem
This example builds on the ticketing app from a previous post.
Let’s flash a message to all visitors when a ticket is added to someone else’s cart.
Adding a ticket, with two separate sessions open:
Problem: We shouldn’t show the alert if we were the ones to add it!
The problem is that the update is broadcast to all connections - including
We want to conditionally hide the message if we were the ones to add the ticket.
To solve this, let’s first inject a dynamic style into our head.
Then, in our “just_added” partial response, we identify the initiating cart -
assuming this identifier is safe to be broadcast.
Success. The message no longer appears for the initiating user:
We can, of course, apply this technique beyond showing and hiding content.
For example, highlighting messages that we sent in a chat app: