A reasonable default CSP for Rails projects
Every modern Rails app should have a Content Security Policy enabled.
Very compatible default
The following "default" is a minimal policy that should
- "just work" for almost all applications
- give you most of the benefits of a CSP
In your config/initializers/content_security_policy.rb
, set
Rails.application.config.content_security_policy do |policy|
policy.object_src :none
policy.script_src :unsafe_eval, :strict_dynamic, :https # Browsers with support for "'strict-dynamic'" will ignore "https:"
po...
Rails: Preloading associations in loaded records
Sometimes you want to fetch associations for an ActiveRecord that you already loaded, e.g. when it has deeply nested associations.
Edge Rider gives your models a static method preload_associations
. The method can be used to preload associations for loaded objects like this:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@user.preload_associations(threads: { posts: :author }, messages: :sender)
end
end
The attached initializers re...
How to debug file system access in a Rails application
It might sometimes be useful to check whether your Rails application accesses the file system unnecessarily, for example if your file system access is slow because it goes over the network.
The culprit might be a library like carrierwave that checks file existence or modification times, whereas your application could determine all this from your database.
Introducing strace
One option it to use strace for this, which logs all system calls performed by a process.
To do this, start your rails server using something like
DISA...
PSA: "index: true" in Rails migrations does not work as you'd expect
Several Rails migration methods accept index: true
as an option to create an index. In some cases (like #add_column
), this option is silently discarded. Know what you are doing, or use #add_index
instead.
Example
Consider the following migration.
class CreateExamples < ActiveRecord::Migration
def change
create_table :examples do |t|
t.references :category, index: true
t.boolean :positive, index: true
t.integer :number_of_participants, index: true
end
add_reference :examples, :user, index: tr...
Auto-generating plain-text bodies for HTML e-mails in Rails apps
When building an application that sends e-mails to users, you want to avoid those e-mails from being classified as spam. Most obvious scoring issues will not be relevant to you because you are not a spammer.
However, your application must do one thing by itself: When sending HTML e-mails, you should include a plain-text body or tools like SpamAssassin will apply a significant score penalty. Here is how to do that automatically.
- Add
premailer-rails
to yourGemfile
andbundle
. - Done! ...
Guide to localizing a Rails application
Localizing a non-trivial application can be a huge undertaking. This card will give you an overview over the many components that are affected.
When you are asked to give an estimate for the effort involved, go through the list below and check which points are covered by your requirements. Work with a developer who has done a full-app localization before and assign an hour estimate to each of these points.
Static text
- Static strings and template text in
app
must be translated: Screens, mailer templates, PDF templates, helpe...
Rails: Fixing the memory leak / performance issues in prepend_view_path
Recently we detected a memory leak in one of our applications. Hunting it down, we found that the memory leak was located in Rails' #prepend_view_path
. It occurs when the instance method prepend_view_path
is called in each request, which is a common thing in a multi-tenant application.
On top of leaking memory, it also causes a performance hit, since templates rendered using the prepended view path will not be cached and compiled anew on each request.
This is not a new memory leak. It was [first reported in in 2014](https://github.com/...
Rails I18n fallback locales
When you need to create a locale for a language variant (like Austrian for German), you probably don't want to duplicate your entire de.yml
file only to change a few minor exceptions for our Austrian friends.
Luckily, the I18n gem used by Rails has a fallback feature where you can make one locale file fall back to another if no translation is available.
In the example above you would have a config/locales/de_DE.yml
:
de_DE:
# hundreds of translations here
... and another...
Rails route namespacing (in different flavors)
TL;DR There are three dimensions you can control when scoping routes:
scope module: 'module', path: 'url_prefix', as: 'path_helper_name' do
resources :examples, only: :index
end
as
→ prefixes path helpers: path_helper_name_examples_path
and path_helper_name_examples_url
path
→ prefixes URL segments: /url_prefix/examples
module
→ nests the controller: controller Module::ExamplesController
, found at app/controllers/module/examples_controller.rb with views in app/views/module/examples/.
These options work with ...
Documenting your Rails project's Node.js version in .nvmrc
Not all versions of Node.js are compatible with each other. Also npm packages may require a minimum or maximum version of Node.js. We use nvm on our development PCs so we can operate multiple versions of Node.js in parallel.
To make sure that all developers use a compatible version of Node.js, your Rails project should declare the required Node.js in a file called .nvmrc
.
When a .nvmrc
exists, developers can cd
in your project directory and activate...
Rails credentials: Always use the bang version
Rails credentials are a way to store secrets in an encrypted YAML file. Usage is simple: each key in the credentials file becomes a method on Rails.application.credentials
, returning the corresponding secret.
# Credentials file
file_storage_secret: superstrongsecret
# Somewhere in the application
FileStorage.secret = Rails.application.credentials.file_storage_secret
Since credentials usually are different between environments, you can easily forget to define them for another environment. If it is an API token, you'll...
Rails: Including HTML in your i18n locales
TL;DR
Append your locale keys with _html to have them marked as
html_safe
and translate them with= t('.text_html')
.
When you're localizing a Rails application, sometimes there is this urge to include a little HTML. Be it some localized link, or a set of <em>
tags, you'd like to have it included in the locale file. Example:
# Locale file
en:
page:
text: 'Please visit our <a href="https://www.corporate.com/en">corporate website</a> to learn more about <em>the corporation</em>.'
# HAML
= t('.text')
# D...
Rails: When to use :inverse_of in has_many, has_one or belongs_to associations
When you have two models in a has_many
, has_one
or belongs_to
association, the :inverse_of
option in Rails tells ActiveRecord that they're two sides of the same association.
Example with a has_many
/ belongs_to
association:
class Forum < ActiveRecord::Base
has_many :posts, inverse_of: :forum
end
class Post < ActiveRecord::Base
belongs_to :forum, inverse_of: :posts
end
Knowing the other side of the same association Rails can optimize object loading so forum
and forum.posts[0].forum
will reference the same o...
How Rails chooses error pages (404, 500, ...) for exceptions
When your controller action raises an unhandled exception, Rails will look at the exception's class
and choose an appropriate HTTP status code and error page for the response.
For instance, an ActiveRecord::RecordNotFound
will cause Rails to render a red "The page you were looking for doesn't exist" with a status code of "404" (not found).
The mapping from exception classes to error types is a hash in Rails.configuration.action_dispatch.rescue_responses
. The...
Rails npm packages will use an uncommon versioning scheme
When Rails releases a new version of their gems, they also release a number of npm packages
like @rails/activestorage
or @rails/actioncable
.
Unfortunately Rails uses up to 4 digits for their gem version, while npm only allows 3 digits and a pre-release suffix.
To map gem versions and npm versions, Rails is going to use a naming scheme like this:
Gem version | npm version |
---|---|
7.0.0 |
7.0.0 |
7.0.1 |
7.0.100 |
... |
Summarizing heredoc in Ruby and Rails
This card tries to summarize by example the different uses of heredoc.
- In Ruby
<<
vs.<<-
vs.<<~
- In Rails
strip_heredoc
vs.squish
strip_heredoc
should be used for a text, where you want to preserve newlines. (multi-line -> multi-line)
squish
should be used for a text, where you want to squish newlines. (multi-line -> one-line)
Ruby 2.3+
def foo
bar = <<~TEXT
line1
line2
line3
TEXT
puts bar.inspect
end
foo => "line1\nline2\nline3\n"
Read more: [Unindent HEREDOCs in Ruby 2.3](/m...
Rails: Configuring the default sorting behaviour
In Rails, the implicit_order_column (added in Rails 6) is a configuration option that helps you define the default sorting behavior of ActiveRecord queries when no explicit ORDER BY
clause is provided. This option allows you to specify a column that Rails will use to automatically sort records in a particular order when no specific ordering is given.
Since the id
is typically the primary key and automatically indexed, Rails will default t...
Ruby / Rails: clone vs. dup vs. deep_dup
Ruby and Rails have several methods for creating a new object that looks like another: clone
, dup
, deep_dup
. When using them you should be aware of their differences so that you can select the method you really need.
clone
- Shallow copy: references to other objects/values are copied (instead of cloning those objects/values)
- Clones the object and all its "special object attributes" like
frozen
,tainted
and modules that the object has been extended with - [Ruby 2.6 documentation for clone](https://devdocs.io/ruby~2.6/obj...
Rails: Different flavors of concatting HTML safe strings in helpers
This card describes different flavors for concatting HTML safe strings in a helper method in Rails. You might want to use the tag helper instead of the content_tag helper (the tag
helper knows all self closing tags).
Example
We want to generate HTML like this:
<h1>Navigation</h1>
<ul>
<li>Left</li>
<li>Right</li>
</ul>
Below you ca...
A simple example with a GIN index in Rails for optimizing a ILIKE query
You can improve your LIKE
/ ILIKE
search queries in PostgreSQL by adding a GIN index with an operate class ("opclass") to split the words into trigrams to the required columns.
Example
class AddSearchTextIndexToUsers < ActiveRecord::Migration[7.1]
def change
enable_extension 'pg_trgm'
add_index :users, :search_tex...
Rails and Postgres: How to test if your index is used as expected
This is a small example on how you can check if your Postgres index can be used by a specific query in you Rails application. For more complex execution plans it might still be a good idea to use the same path of proof.
1. Identify the query your application produces
query = User.order(:last_name, :created_at).to_sql
puts query
# => SELECT "users".* FROM "users" ORDER BY "users"."last_name" ASC, "users"."created_at" ASC
2. Add an index in your migration and migrate
add_index :users, [:last_name, :created_at]...
Custom error pages in Rails
Basic error pages
To add a few basic styles to the default error pages in Rails, just edit the default templates in public
, e.g. public/404.html
.
A limitation to these default templates is that they're just static files. You cannot use Haml, Rails helpers or your application layout here. If you need Rails to render your error pages, you need the approach below.
Advanced error pages
- Register your own app as the applicatio...
Zeitwerk: How to collapse folders in Rails
All direct child directories of app
are automatically added to the eager- and autoload paths. They do NOT create a module for namespacing. This is intuitive, since there normally is no module Model
, or module Controller
. If you want to add a new base directory, there's no additional config needed.
Example
app
├── controllers
├── helpers
├── inputs # No config needed
├── mailers
├── models
├── uploaders # No config needed
├── util # No config needed
└── workers # No config needed
Sometimes it's handy to group files wit...
Rails Partials
Rails partials have a lot of "hidden" features and this card describes some non-obvious usages of Rails Partials.
Rendering a basic partial
The most basic way to render a partial:
render partial: 'partial'
This will render a _partial.html.erb
file. Notice how all partials need to be prefixed with _.
It's possible to define local variables that are only defined in the partial template.
# _weather.html.erb
<h1>The weather is <%= condition %></h1>
# index.html.erb
render partial: 'weather', locals: { condition: ...