class ShippedEmailJob
include Sidekiq::Job
sidekiq_options queue: :mailers, retry: 5
def perform(order_id)
order = Order.find_by(id: order_id)
return if order.nil?
OrderMailer.shipped(order).deliver_now
end
end
class ShippedSmsJob
include Sidekiq::Job
sidekiq_options queue: :sms, retry: 3
def perform(order_id)
order = Order.find_by(id: order_id)
return if order.nil? || order.customer.phone.blank?
body = "Order ##{order.number} shipped. Track: #{order.tracking_number}"
SmsClient.send_message(to: order.customer.phone, body: body)
end
end
class Order < ApplicationRecord
belongs_to :customer
enum state: { pending: 0, paid: 1, shipped: 2, delivered: 3 }
validates :tracking_number, presence: true, if: :shipped?
after_commit :notify_shipped, on: :update
private
def notify_shipped
return unless saved_change_to_state? && shipped?
OrderNotifier.order_shipped(self)
end
end
module OrderNotifier
module_function
def order_shipped(order)
channels_for(order).each do |worker|
worker.perform_async(order.id)
end
end
def channels_for(order)
workers = [ShippedEmailJob]
workers << ShippedSmsJob if order.customer.sms_opted_in?
workers
end
end
This snippet shows how a single domain event — an Order transitioning to a shipped state — can fan out to multiple notification channels without cluttering the model with delivery logic. The pattern separates what happened (a state change) from what should happen next (email, SMS), keeping the model thin and the channels independently testable and retryable.
In Order model, the after_commit callback is the trigger. Committing only after the transaction lands is deliberate: enqueuing work before the row is durable risks a background worker reading a record that never got persisted, a classic race that produces phantom notifications. The saved_change_to_state? guard plus the shipped? check ensures the observer only reacts on the transition into shipped, not on every save. The model deliberately knows nothing about email or SMS; it merely announces the change to OrderNotifier.
OrderNotifier observer is the fan-out hub. Its order_shipped method enqueues one background job per channel via Sidekiq. Fanning out here rather than in the model means new channels (push, Slack, webhooks) can be added in one place, and each channel fails and retries in isolation — an SMS provider outage never blocks the email. Enqueuing job IDs rather than full objects keeps payloads small and forces each worker to reload fresh state.
NotificationJobs contains the two workers. sidekiq_options sets bounded retry counts appropriate to each channel, and each job reloads the Order by id, so it always operates on current data even if the record changed between enqueue and execution. The find_by guard tolerates a deleted order, letting the job succeed as a no-op instead of raising and burning retries.
The key trade-off is eventual consistency: notifications are asynchronous, so a user may see the shipped status slightly before the email arrives. In exchange the request stays fast and channel failures are contained. A subtle pitfall is after_commit firing again on subsequent saves, which the state-change guard prevents. This structure suits any system where one event drives several side effects that must not be coupled to the write path — order updates, signups, or payment confirmations.
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.