My link directory and notes for Rails stuff. As usual, work in progress.
Admin interfaces
APIs
- Apipie
- bblimke/webmock: Library for stubbing and setting expectations on
- Building your own API with Rails - Learn Interactively
- Building High Performance Ruby REST APIs with Rage
Authorization
- Authentication / Authorization
- An Introduction to Auth0 for Ruby on Rails
- GitHub - enjaku4/rabarber: Simple authorization library for Ruby on Rails
rails g sessions
Bundling
Caching
- An Introduction to HTTP Caching in Ruby On Rails
- rails/solid_cache: A database-backed ActiveSupport::Cache::Store
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
- https://businessclasskit.com (SaaS with Gumroad integration)
CSS
Database
Debugging
- Prosopite is able to auto-detect Rails N+1 queries
Development
- https://github.com/lape/devcontainer-rails
- github/scientist: A Ruby library for carefully refactoring critical paths.
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
- https://github.com/hopsoft/rails_standards
- Well-written code examples by 37signals
- https://railsinspire.com/
- Boring Rails
- ankane/production_rails: Best practices for running Rails in production
- eliotsykes/real-world-rails: Real World Rails applications and their open source codebases for developers to learn from
Jobs
Solid Queue
- https://mileswoodroffe.com/articles/solid-queue-and-mission-control
- https://dev.37signals.com/introducing-solid-queue
- https://github.com/rails/mission_control-jobs
- https://www.driftingruby.com/episodes/processing-large-jobs
- SOLID_QUEUE_IN_PUMA=1
Logging
Honeybadger.event("SUCCESS",
{ message: "A new customer just signed up" })
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
PostgreSQL
Proxy
37signals Dev — Thruster HTTP/2
Redis
How to use Redis with Rails? - Stack Overflow
Rich Text
Routing
Security
Rack Attack
rate_limit to: 5, within: 1.minute, only: :create
Scraping
https://github.com/glaucocustodio/tanakai
Storage
# Purge orphan files and blob records
ActiveStorage::Blob.unattached.each(&:purge)
SQLite
- https://github.com/fractaledmind/litestream-ruby
- Must have (according to Stephen Margheim at RailsConf 2024): https://github.com/fractaledmind/activerecord-enhancedsqlite3-adapter
- https://github.com/fractaledmind/litestream-ruby
Testing
- Environment variables with climate_control
- https://buttondown.com/kaspth/archive/why-is-oaken-for-your-database-seeds-test-data/
- Exploring the FFaker Gem - A Comprehensive Guide | Shakacode
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 } %>