ruby 56 lines · 3 tabs

Fan Out Notifications to Email and SMS Using an ActiveRecord Observer

Shared by codesnips Aug 2026
3 tabs
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
3 files · ruby Explain with highlit

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

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
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

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
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

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<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)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Fan Out Notifications to Email and SMS Using an ActiveRecord Observer — share card
Link copied