Rails: Invoking a view helper from the console

There are a few ways to access view helpers from the Rails console. The easiest way is the helper shortcut:

helper.translate 'i18n.string'

If the desired helper renders a view template, you need this setup:

view_paths =["app/views"]
av_helper = YourHelperModule


Rails routing: Using constraints to avoid "Missing template" errors

You can use constraints in your routes.rb to avoid getting errors when wrong routes are called. Instead, the user will see a 404.

If you want multiple routes to use the same constraint you can use the block syntax:

constraints(format: 'html') do
  resources :pages
  resources :images

If you want constraints only on certain routes, you can do:

get '/users/account' => 'users#account', constraints: { format: 'html' }

Note: You can also avoid this error through format constraints in your controllers.


Capistrano: How to find out which version of your application is currently live

When deploying, Capistrano puts a REVISION file into your application's release directory. It contains the hash of the commit which was deployed.

If you want to know the currently deployed release, simply SSH to a server and view that file.

$ cat /var/www/my-project/current/REVISION

Capistrano task

When your application is deployed to multiple servers, you probably want to see a result for all of them.
Here is a Capistrano task that checks all servers with the :app role.



JavaScript: Testing the type of a value

Checking if a JavaScript value is of a given type can be very confusing:

  • There are two operators typeof and instanceof which work very differently.
  • JavaScript has some primitive types, like string literals, that are not objects (as opposed to Ruby, where every value is an object).
  • Some values are sometimes a primitive value (e.g. "foo") and sometimes an object (new String("foo")) and each form requires different checks
  • There are three different types for null (null, undefined and NaN) and each has different rules for…

Understanding race conditions with duplicate unique keys in Rails/MySQL

validates_uniqueness_of is not sufficient to ensure the uniqueness of a value. The reason for this is that in production, multiple worker processes can cause race conditions:

  1. Two concurrent requests try to create a user with the same name (and we want user names to be unique)
  2. The requests are accepted on the server by two worker processes who will now process them in parallel
  3. Both requests scan the users table and see that the name is available
  4. Both requests pass validation and create a user with the seemingly available name…

Cancelling event propagation

Within an event handler, there are multiple methods to cancel event propagation, each with different semantics.

  • event.preventDefault()

    Only prevents the default browser behavior for the click, i.e. going to a different url or submitting a form.

  • event.stopPropagation()

    Prevents the event from bubbling up the DOM. Note this effectively also cancels any event handlers attached through jQuery's live method, since those depend on bubbling.

  • event.stopImmediatePropagation()

    Prevents the event from triggering any remaining…


An auto-mapper for ARIA labels and BEM classes in Cucumber selectors

Spreewald comes with a selector_for helper that matches an English term like the user's profile into a CSS selector. This is useful for steps that refer to a particular section of the page, like the following:

Then I should see "Bruce" within the user's profile

If you're too lazy to manually translate English to a CSS selector by adding a line to features/env/selectors.rb, we already have an [auto-mapper to translate English into …

Haml: Prevent whitespace from being stripped in production


This is not an issue in newer versions of HAML (starting with 5.0.0), as the ugly-option was removed so that in development everything is rendered ugly, too.


When HTML is rendered from HAML in production or staging environment, whitespace is removed to reduce the download size of the resulting pages. Therefore it might happen that whitespace you see in development is missing in production or staging.

Here is an example of two inlined bootstrap buttons in a t…


Thread-safe collections in Ruby

When using threads, you must make your code thread-safe. This can be done by either locking (mutexes) all data shared between threads, or by only using immutable data structures. Ruby core classes like String or Array are not immutable.

There's several gems providing thread-safe collection classes in Ruby.


The concurrent-ruby gem provides thread-safe versions of Array and Hash:

sa = # supports standard forms
sh = Conc…


Controlling how your website appears on social media feeds

When a user shares your content, a snippet with title, image, link and description appears in her timeline. By default social networks will use the window title, the first image, the current URL and some random text snippet for this purpose. This is often not what you want.

Luckily Facebook, Twitter, etc. lets you control how your content appears in the activity streams. They even have agreed on a common format to do this: OpenGraph <meta> tags that go into your HTML's <head>:

<meta property="og:url" content="http://start.makan...

Unpoly: Automatically show the full better_errors page when Rails raises an error

When an AJAX request raises an exception on the server, Rails will show a minimal error page with only basic information. Because all Unpoly updates work using AJAX requests, you won't get the more detailled better_errors page with the interactive REPL.

Below is an event listener that automatically repeats the request as a full-page load if your development error shows an error page. This means you get…


CSS: Don't target multiple vendor-prefixed pseudo-elements in a single rule

Some pseudo-elements need to be addressed with vendor prefixes. E.g. ::selection is not supported by Firefox, you need to use ::-moz-selection instead.

What you cannot do is to define a single CSS rule to address both the standard and vendor-prefixed form:

::selection, ::-moz-selection {
  background-color: red;

This rule will be ignored by all browsers. The reason is that if a browser doe…

Linked content

CSS font metrics in detail

Line-height and vertical-align are simple CSS properties. So simple that most of us are convinced to fully understand how they work and how to use them. But it’s not. They really are complex, maybe the hardest ones, as they have a major role in the creation of one of the less-known feature of CSS: inline formatting context.

For example, line-height can be set as a length or a unitless value 1, but the default is normal. OK, but what normal is? We often read that it is (or should be) 1, or maybe 1.2, even the CSS spec is unclear on that…

Linked content

How to inspect the HTML of an email in Thunderbird

Inspecting the source of an email does not always reveal the plain HTML source, but some encoded byte mess. In order to inspect the HTML anyways, you can use a little trick:

While composing a message, select all (Ctrl + A), then navigate to Insert > HTML on the message window.

If you need to inspect a received message, hit "Reply" to turn it into composition mode.


Jasmine: using async/await to write nice asynchronous specs

Jasmine has long standing support for writing asynchronous specs. In days gone by we used the done callback to achieve this, but these days it is possible to write much more readable specs.

Async specs

As a first example, say we want to check that some form disables the submit button while working.

// bad (how we used to do it)

beforeEach(() => {
this.form = setupMyForm()
this.submitButton = findTheSubmitButton()

it('disables the submit button while working', (done) => {
expect(this.submitButton.disabled).toBe(false) …

Adding Jasmine JavaScript specs to a Webpack(er) project

The goal is to get Jasmine specs running in a Rails project using Webpacker, with the browser based test runner. Should be easily adaptable to a pure Webpack setup.


Step 1: Install Jasmine

yarn add jasmine-core

Step 2: Add two separate packs

Since we do not want to mix Jasmine into our regular Javascript, we will create two additional packs. The first only contains Jasmine and the test runner. The second will contain our normal application code and the specs themselves.

We cannot…


ActiveType 1.2 supports "change_association"

With ActiveType 1.2 you can modify associations (has_many etc.) after they have been defined.

One common use case for this is to change an association inside a form model, like this:

class Credential < ActiveRecord::Base

class User < ActiveRecord::Base
  has_many :credentials

class SignUpCredential < ActiveType::Record[Credential]

class SignUp < ActiveType::Record[User]
  change_association :credentials, class_name: 'SignUpCredential'

Now, if you load credentials, y…

Linked contentDeprecated Super-simple favicon generator

Eduardo Russo was tired of complex favicon creation and created his own favicon generator. It's really easy and allows a lot of image editing before rendering the favicons, in all needed sizes, formats and with the HTML needed to include them!

In Rails applications with Haml:

  • put all the favicon files into /public
  • store the HTML to app/views/layouts/_favicon.html
  • add = render 'layouts/favicon' to <head> in your application layout(s)

… and you're all…

This website uses cookies to improve usability and analyze traffic.
Accept or learn more