ActionMailer: Preview mails directly in your email client

In rails, we usually have a mailer setup like this:

class MyMailer < ActionMailer::Base

  def newsletter
    mail to: 'receiver@host.tld,
      from: 'sender@host.tld',
      subject: 'My mail'


If you want to preview your mail in the browser, you can use the Action Mailer Preview. If you want to inspect your mail directly in your email client, just create an .eml file and open it with your client:

mail = MyMailer.newsletter…


Authorize allowed values with assignable_values

All our projects have enum-like requirements like this:

  • An attribute value must be included in a given set of values.
  • The list of allowed values must be retrievable in order to render <select> boxes.
  • Each value has a humanized label.
  • Sometimes there is a default value.

Most of the time, this requirement is also needed:

  • The list of assignable values depends on the user who is currently signed in.

In our past projects there are many different solutions for these related requirements, e.g. ChoiceTrait, methods like `available_…


Custom error pages in Rails 3.2+

Starting with Rails 3.2, there is a nicer way to display custom error pages (i.e. "page not found") that does not interfere with ExceptionNotifier. (I'm not sure about Airbrake et al.)

José Valim has posted this on his blog, here is a slightly more verbose rundown:

  1. Register your own app as the application responsible for showing error pages by adding

    config.exceptions_app = self.routes

    to your config/application.rb.

  2. Add rout…

Using local fonts with Webpack / Webpacker

When we want to use our own (or bought) fonts in an application with Webpack(er), we have two options. We can

  • put the fonts directly into your Webpack's assets folder or
  • write an npm package with an own sass file that can be imported from the Webpack manifest.

Load fonts from your assets folder

The first option turns out to be straightforward: Import the stylesheets in the index.js of the pack you're using:

// webpack_source_path/application/index.js

import './stylesheets/reset'


Rails: Passing array values to tag helpers like link_to

From at least Rails 4, the ActionView tag helper turns Array values of HTML options into a single space-separated string.
This means you can pass an array to :class options:

extra_classes = %w[one two]

= link_to 'Dashboard', root_path, class: ['btn', 'btn-primary', *extra_classes]
=> Dashboad

= content_tag 'div', 'Hello World', class: %w[alert alert-info]
=> <div class="alert alert-info">Hello World</div>

= …

Upgrade guide for moving a Rails app from Webpack 3 to Webpack 4

Webpacker is Rails' way of integrating Webpack, and version 4 has been released just a few days ago, allowing us to use Webpack 4.

I successfully upgraded an existing real-world Webpack 3 application. Below are notes on everything that I encountered.
Note that we prefer not using the Rails asset pipeline at all and serving all assets through Webpack for the sake of consistency.


  • Remove version locks in Gemfile for webpacker
  • Remove version locks in package.json for webpack and webpack-dev-server
  • Install by ca…

Running external commands with Open3

There are various ways to run external commands from within Ruby, but the most powerful ones are Open3.capture3 and Open3.popen3. Since those can do almost everything you would possibly need in a clean way, I prefer to simply always use them.

Behind the scenes, Open3 actually just uses Ruby's spawn command, but gives you a much better API.


Basic usage is

require 'open3'

stdout_str, error_str, status = Open3.capture3('/some/binary', 'with', 'some', 'args')
if status.success?…


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…

Micro clearfix mixin for Sass

Clearfix is a hack to clear floating elements without additional HTML markup.

If you only need to support IE8 and above, a great clearfix with few side effects is:

    content: ""
    display: block
    clear: both

This is a Sass mixin.

Issues clearing with display: table

You will find many clearfix solutions that clear with display: table instead:

    content: ""
    display: table
    clear: both

The problem with th…

Linked content

Copy to clipboard without flash (clipboard.js)

We used zeroclipboard.js in some of our projects but now we switched to clipboard.js because it does not rely on flash. Flash support of the major browsers has ended.

Some more advantages of clipboard.js:

  • it consists only of a single javascript file, so it does not trigger additional requests with rails
  • it automagically provides user feedback by selecting the text it has copied
  • it provides callbacks for success and error which make it easier to add custom behaviour after copying to the clipboar…

JavaScript without jQuery (presentation from 2019-01-21)


  • We want to move away from jQuery in future projects
  • Motivations are performance, bundle size and general trends for the web platform.
  • The native DOM API is much nicer than it used to be, and we can polyfill the missing pieces
  • Unpoly 0.60.0 works with or without jQuery

Is jQuery slow?

From: Sven
Subject: performance on smartphones and tablets


I just used your framework in one project and must say,
I am really pleased with it – but only on a desktop computer.

Have you benchm…

Linked contentRepeats

Rails 4 introduced collection_check_boxes

Starting from Rails 4.0, you can use a special form options helper called #collection_check_boxes. It behaves similar to #collection_select, but instead of a single select field it renders a checkbox and a label for each item in the collection.

= form_for @post do |form|
  = form.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial

How generated form params look like ———————————…

Carrierwave: Built-in resize methods

Carrierwave includes some handy helper methods you can use to resize your images. Here is a quick summary of them, if you need more details read the docs. You can also use all command line options from RMagick directly if these helpers are not good enough for you.

resize_to_limit(width, height)
resize_to_fit(width, height)


Capybara will not find links without an href attribute

Capybara will fail to find <a> tags that are missing an href attribute. This will probably happen to you every now and then on JavaScript-heavy applications.

An example would be an AngularJS application where the following HTML actually works. [1]

<a ng-click="hello()">Hello</a>

Capybara will fail to find that link, even though looking it up via the DOM shows it:

>> find_link("Hello")
Capybara::ElementNotFound: Unable to find link "Hello"

>> find("a").text
=> "Hello"

To make find_link and click_link work…


How not to turn your application into a spam relay

Spammers have started abusing other application to send their spam. This works like this:

  • The application has some form that allows to send e-mails to arbitrary users. This can be something like a newsletter sign-up with a double-opt in, a registration confirmation e-mail (or even password reset e-mail), or something similar.
  • The e-mail also includes some reflected text. For example, a user may be able to give their name, and the name is used within the e-mail. The spammer will then abuse that text to include his advertisment.



How to use Rails URL helpers in any Ruby class

In Rails 3+, you can use:

class Project
  delegate :url_helpers, to: 'Rails.application.routes'

  def project_path

For Rails 2, use the attached Modularity trait. It will give any Ruby class a method #url_writer, on which you can call URL helpers:

class Foo
  does 'write_urls'
  def self.class_method
  def instance_method

Ruby: Natural sort strings with Umlauts and other funny characters

Why string sorting sucks in vanilla Ruby

Ruby's sort method doesn't work as expected with German umlauts:

["Schwertner", "Schöler"].sort
=> ["Schwertner", "Schöler"] # you probably expected ["Schöler", "Schwertner"]

Also numbers in strings will be sorted character by character which you probably don't want:

["1", "2", "11"].sort
# => ["1", "11", "2"] # you probably expected ["1", "2", "11"]

Also the sorting is case sensitive:

["a", "B"].sort
# => ["B", "a"] # yo...

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.

  1. Add premailer-rails to your Gemfile and bundle.
  2. Done! …
This website uses cookies to improve usability and analyze traffic.
Accept or learn more