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

Don’t have an account yet? Sign up.

Latest Samples

Inertia V2 + Rails - Infinite Scroll
How to implement InfiniteScroll with Inertia V2 + Rails + Rails
class TodosController < ApplicationController

  # GET /todos or /todos.json
  def index
    @pagy, @todos   = pagy(Todo.all, limit: 10)
Curated ago by @pedroaugustorduarte
Adding custom Active Storage transformations
Out of the box, Active Storage supports a number of transformations, through the image_processing gem. This gem provides a common interface to both MiniMagick (the old standard) and ruby-vips (the new default). I recently needed the ability to lighten images uploaded via Active Storage (for use as watermarks), but there...
<% if @document.watermark.attached? %>
  <%= image_tag @document.watermark.variant({ resize_to_limit: [1_000, 1_000], lighten: 0.5 }) %>
<% end %>
Curated ago by @jeremysmithco
Uploading Honeybadger source maps with esbuild and Sprockets
If you are using Honeybadger for JS error monitoring on your Rails app, you may want to upload source maps so they can be applied to JS stack traces. Here's how you can do that if you are using esbuild, Sprockets, and deploying to Heroku. The source map will be...
<script src="//js.honeybadger.io/v6.9/honeybadger.min.js" type="text/javascript"></script>
<script type="text/javascript">
  Honeybadger.configure({
    apiKey: "<%= ENV["HONEYBADGER_API_KEY_JS"] %>",
    environment: "<%= ENV["HONEYBADGER_ENV"] %>",
Curated ago by @jeremysmithco
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)
  end
end
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)
end
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

Categories