Ruby on Rails resources

My link directory and notes for Rails stuff. As usual, work in progress.

Ruby on Rails resources
Photo: Alexander Sinn / Unsplash

My link directory and notes for Rails stuff. As usual, work in progress.

Admin interfaces

APIs

Authorization

rails g sessions

Bundling

Caching

Memcache

def get_ops client_id
  latest_import = ImportLog.maximum :updated_at
  cache_tag = "ops-#{client_id}-#{latest_import.iso8601}"
  Rails.cache.fetch(cache_tag, expires_in: 1.day) do
    Rails.logger.info("Cache miss for #{cache_tag}")
    Op.where(client_id: client_id).to_json
  end
end

CAPTCHA

CLI

  • TableTennis is a Ruby library for printing stylish tables in your terminal

Concurrency

# Subprocess
pid = Process.fork do 
  long_process
end
Process.detach pid

Config

ActiveSupport::Configurable

Commerce

CSS

Database

Debugging

  • Prosopite is able to auto-detect Rails N+1 queries

Development

Documentation

Error Reporting and Exception Handling

  • Solid Errors is a DB-based, app-internal exception tracker for Rails applications, designed with simplicity and performance in mind.

Files and Storage

# tempfiles
Tempfile.open("voucher", Rails.root.join("tmp")) do |f|
  f.print(price.name)
  f.flush
end

Forms

https://github.com/heartcombo/simple_form

Date Picker

<%= f.text_field :birthday, label: t(:form_birthday),
    floating: true, required: true,
    data: {
      controller: "flatpickr",
      flatpickr_date_format: "d.m.Y",
      flatpickr_min_date: "1900-01-01",
      flatpickr_allow_input: true,
    }
%>

Frontend

Generators

rails g scaffold_controller
rails g migration addAddressToOps address:reference

Hosting

Howtos/Guides

Jobs

Solid Queue

Logging

Honeybadger.event("SUCCESS", 
  { message: "A new customer just signed up" })

Mail

Migration

https://www.akshaykhot.com/rails-database-migrations-cheatsheet/

Load schema instead of migrations

rake db:schema:load

If you're on the latest (8) version of Ruby on Rails, there's a nice shortcut to add the not null modifier to your database columns. Just add an exclamation mark after the type, and Rails will mark that column as not null. 

rails generate migration CreateUsers \
  email_address:string!:uniq password_digest:string!

MySQL

ALTER USER 'opos'@'localhost' \
  IDENTIFIED WITH mysql_native_password BY 'opos';

Multiple Databases with Active Record — Ruby on Rails Guides

# models/application_record.rb     
class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class
  connects_to database: {writing: :primary, reading: :primary_replica}
end

Indices

Exclude nulls from indexes            

A database index is a B-tree structure. It is very efficient when data has a high cardinality. However, when a column allows nulls, it often becomes the most redundant value. The index is less efficient and takes up more space. Unless null is an infrequently repeated value, there are only disadvantages to indexing them.

Exclude them when creating the index with a where clause.

add_index :table, :column, where: "(column IS NOT NULL)"

 Or in pure SQL :              

CREATE INDEX name ON table (column) \
  WHERE column IS NOT NULL;

Do not index column with a low cardinality such as boolean              

The reason is the same as in the previous paragraph. B-tree indexes work best when cardinality is high. So a Boolean is the worst column you can index. So don’t index booleans.

As with other types, if you have very repetitive values that are not significant from a business point of view, it’s probably a good idea to exclude

PDF

PostgreSQL

Proxy

37signals Dev — Thruster HTTP/2

Redis

How to use Redis with Rails? - Stack Overflow

Rich Text

https://dante-editor.dev

Routing

Rails Router Handbook

Security

Rack Attack

Rate Limiting

rate_limit to: 5, within: 1.minute, only: :create

Scraping

https://github.com/glaucocustodio/tanakai

Stimulus and Hotwire

Better StimulusJS Examples

Storage

# Purge orphan files and blob records
ActiveStorage::Blob.unattached.each(&:purge)

SQLite

Testing

Minitest

# test_helper.rb
# Set up minitest-reporters to show a 
# spec-style progress report.
require "minitest/reporters"
Minitest::Reporters.use! 
  [Minitest::Reporters::SpecReporter.new]

 Capybara System Tests

 bin/rails generate system_test users

Test Coverage

# test_helper.rb
require "simplecov"
SimpleCov.start "rails"

Templates/ERB

Disable Turbo

<%= link_to l.to_s.upcase, "/#{l}", 
  class: ("active" if locale == l), 
  data: {"turbo": false } %>

Updating

Read next