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

Don’t have an account yet? Sign up.

Latest Samples

Rendering Markdown with Multiple Modes
Sometimes when I'm working with Markdown in a Rails app, I'll be using different sets of redcarpet flags for different types of content. For example, I have images and links turned on for blog posts, but turned off for comments. Keeping track of all the variations can be difficult. I...
module MarkdownHelper
  def render_markdown(content, mode)
    sanitize(MarkdownRenderer.new(content, mode).render)
Curated ago by @jeremysmithco
Alternative approach to drag and drop sorting with acts_as_list
Here's an somewhat unconventional approach to drag and drop sorting using acts_as_list I came up with this week. In the old days, I would have implemented something similar to this RailsCasts episode. But I think I might like this better. I made a YouTube video explaining my thinking. As Chris...
class ListInsertionsController < ApplicationController
  def create
    item = GlobalID::Locator.locate(params[:item])
    precursor = GlobalID::Locator.locate(params[:precursor])
    authorize item, :update?
Curated ago by @jeremysmithco
View Component sidecar generator
rails g view_component NomeDoComponente with stimulus: rails g view_component NomeDoComponente --stimulus File: - component.html.erb html for the component - component.rb ruby code for internal component logic - preview.rb preview for lookbook - /spec/component_spec.rb spec for component with rspec
<div<%= data_attributes %>>Add <%= class_name %> template here</div>
Curated ago by @pedroaugustorduarte
Credentials or env
A simple helper that selects some configuration from credentials or environment variable
# frozen_string_literal: true

module Credentials
  # Returns credentials or env
  # OBS: Does not support nested credentials
Curated ago by @pedroaugustorduarte
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