real-time

ruby
class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :author, class_name: "User"

  validates :body, presence: true, length: { maximum: 5_000 }

Declarative model broadcasts with broadcasts_to (Rails 7)

rails hotwire turbo
by codesnips 4 tabs
ruby
class ReportsController < ApplicationController
  def create
    @report = current_user.reports.create!(
      title: report_params[:title],
      status: :pending,
      progress: 0

Turbo Streams: broadcast from a job for long operations

rails turbo hotwire
by codesnips 3 tabs
javascript
const { EventEmitter } = require('events');

class NotificationBus extends EventEmitter {
  constructor(bufferSize = 100) {
    super();
    this.setMaxListeners(0);

Server-Sent Events for Live Notifications with a Reconnectable EventSource Hook

sse server-sent-events eventsource
by codesnips 3 tabs
ruby
class ImportRun < ApplicationRecord
  enum status: { pending: 0, running: 1, completed: 2, failed: 3 }

  def percent
    return 0 if total.to_i.zero?
    [(processed.to_f / total * 100).round, 100].min

Live Turbo Streams Progress Bar for a Long Rails Job

rails turbo-streams hotwire
by codesnips 4 tabs
ruby
class LikesController < ApplicationController
  before_action :set_post

  def create
    @like = current_user.likes.create!(post: @post)
    respond(liked: true)

Turbo Streams: swap a button state and counter in one response

rails hotwire turbo
by codesnips 4 tabs
ruby
class PresenceRegistry
  TTL = 30 # seconds a user counts as present without a heartbeat

  def initialize(room_id, redis: REDIS)
    @room_id = room_id
    @redis = redis

Action Cable Presence Tracking (Lightweight)

rails actioncable redis
by codesnips 3 tabs
ruby
class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :author, class_name: "User"

  validates :body, presence: true

Model broadcasts: prepend on create, replace on update

rails hotwire turbo-streams
by codesnips 4 tabs
erb
<%# Subscribe every viewer of this post to its broadcasts %>
<%= turbo_stream_from @post %>

<%# Update the acting user's button to reflect the toggle %>
<%= turbo_stream.replace dom_id(@post, :like_button) do %>
  <%= render "posts/like_button", post: @post %>

Live counter updates with Turbo Streams (likes, votes)

rails hotwire turbo
by codesnips 4 tabs