A curated collection of code samples from Ruby on Rails projects.

Don’t have an account yet? Sign up.

Latest Samples

Multiple Active Storage Services with Override for Test
Active Storage services default to private access, unless you specifically make them public. By default, Active Storage assumes private access to services. This means generating signed, single-use URLs for blobs. If you'd rather make blobs publicly accessible, specify public: true in your app's config/storage.yml But sometimes apps need both private...
class Account < ApplicationRecord
  has_one_attached :logo, service: storage_service(:amazon_public)
  has_one_attached :report, service: storage_service(:amazon_private)
Curated ago by @jeremysmithco
Extract bright colors from an image
Sometimes you need to pull out a color from an image. This could be for a placeholder, for a background, or for any other use. Often the "most common" color from an image is going to be shades of grey or brown – not the most exciting color to expand on....
class ColorExtractor
  attr_accessor :source_url

  DEFAULT_COLOR = '#4338CA'.freeze # indigo-700

Curated ago by @adam
Background workers for Interactors
This is a simple pattern I use all the time to organize my interactors and background workers. The interactor holds the business logic and the work simply invokes it. It works great when you start with the logic and as it grows in runtime, put it into a background worker...
class DoWork
  include Interactor

  delegate :name, to: :context

Curated ago by @dpaola2
User Live Search with Stimulus, Turbo Frames and PgSearch
Here's a solution I've used on a project to add a user switcher dropdown with typeahead search to a navbar. It uses the pg_search gem for Postgres full-text search. There are a lot of blog posts out there with similar solutions, with terms like: typeahead, autocomplete, autosuggest, instant search.
class UsersSearchesController < ApplicationController
  def index
    @users = users_query(params[:query])

    respond_to do |format|
Curated ago by @jeremysmithco
Less Annoying Sidekiq Bugsnag Errors
This middleware makes Bugsnag ignore network connection errors raised from Sidekiq jobs. Instead of reporting errors to Bugsnag every time the job retries, we only report these errors if/when the job finally dies. The goal is to eliminate extra noise caused by transient network errors.
class BugsnagSidekiqDeathHandler
  def self.handler
    ->(_job, exception) do
      # The <= operator returns true if the class on the left is the same as OR a subclass of the class on the right
      if BugsnagSidekiqMiddleware::IGNORED_EXCEPTIONS.any? { |e| exception.class <= e }
Curated ago by @pelargir
Generating Open Graph Images with SVG partial and Vips
I found a way to generate custom Open Graph images for Sample files on this site using an SVG partial that is rendered and converted to PNG by ImageProcessing::Vips.
class SampleFile < ApplicationRecord
  has_one_attached :open_graph_image

  def update_open_graph_image
    self.open_graph_image.attach(io: CreateSampleFileImage.new(self).create, filename: "sample_file_#{id}.png")
Curated ago by @jeremysmithco
Minification with Both Uglifier and esbuild
If you are working on legacy Rails projects with old ES5 code, but have also switched to jsbundling-rails, esbuild for new ES6 code, you may have struggled to find a good approach to minifying all your assets. Uglifier only works with ES5 and may cause issues in Harmony mode. Inspiration...
//= link_tree ../builds
//= link_tree ../images
//= link legacy.js
Curated ago by @jeremysmithco
Service Object Interface
Simple example on how to implement the typical .call interface for plain ruby service objects.
class User
  def greet
Curated ago by @vaporyhumo
Roll Your Own Audit Logging
Here's a simple audit logging solution using an AuditLog ActiveRecord model with a polymorphic association, a Sidekiq worker, and an audit_log controller method. I wrote about the approach in Audit Logging in Rails.
class ApplicationController < ActionController::Base
  def audit_log(auditable, account, event)
    AuditLogWorker.perform_async(auditable.to_global_id, account.id, current_user.id, event)
Curated ago by @jeremysmithco
Open Delivered Emails in Dev Email Client (Mac-only)
Rails bin script to listen for emails delivered to filesystem and open with Mail (on a Mac).
#!/usr/bin/env ruby
require 'listen'

# This script watches for ActionMailer mail delivered to tmp/mails in dev,
# adds a timestamp and proper extension to the filename, and opens in the
Curated ago by @jeremysmithco