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…

SASS: Defining linear sizes

Just dumping this in case somebody might need it.

When you need a CSS value (a padding, margin, height etc) to shrink/grow proportionally with the parent element, you normally use percentage values. However, if you need specific values at two given widths, you need to turn to linear functions. The mixin below gives you just that.

// Call with two desired values at two different widths.
// Returns a calc() expression that will scale proportionally between those two.
// Example:
// Spaci…

External content

The pitfalls of postMessage

The postMessage API is an alternative to JSONP, XHR with CORS headers and other methods enabling sending data between origins. It was introduced with HTML5 and like many other cross-document features it can be a source of client-side vulnerabilities.


RestClient / Net::HTTP: How to communicate with self-signed or misconfigured HTTPS endpoints

Occasionally, you have to talk to APIs via HTTPS that use a custom certificate or a misconfigured certificate chain (like missing an intermediate certificate).

Using RestClient will then raise RestClient::SSLCertificateNotVerified errors, or when using plain Net::HTTP:

OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Here is how to fix that in your application.

Important: Do not disable certificate checks for production. The interwebs are full of people say…


Don't run bundle update without arguments

Calling bundle update (without arguments) updates all your gems at once. Given that many gems don't care about stable APIs, this will break your application in a million ways. Don't do it.

Instead you should:

  1. Update a single gem conservatively
  2. Run tests
  3. Deal with the pain
  4. Update the next gem

It's also advisable to only update gems for a good reason (security fixes, new features you want), unless you like pain.


Security issues with hash conditions in Rails 2 and Rails 3

Find conditions for scopes can be given either as an array (:conditions => ['state = ?', 'draft']) or a hash (:conditions => { 'state' => 'draft' }). The later is nicer to read, but has horrible security implications in some versions of Ruby on Rails.

Affected versions

Version Affected? Remedy
2.3.18 yes Use chain_safely workaround
3.0.20 no

Know your Haml comments

There are two distinct ways of commenting Haml markup: HTML and Ruby.

HTML comments

This will create an HTML comment that will be sent to the client (aka browser):

/= link_to 'Example', '' # => <!-- = link_to 'Example', '' -->

Only use this variant if you need the comment to appear in the HTML.

Ruby comments

This will comment code so it will not be sent to the client:

-# = link_to 'foo'

99% of the time you'll be adding notes for other developers, or disabling code sections that should…

How to show an ordered crontab

Crontabs are often unordered, especially when generated for an application where you usually group tasks by their domain/scope.

An example crontab might look like this:

# Begin Whenever generated tasks for: project100

# When server is booting up, ensure Sidekiq is running
@reboot start_sidekiq

23 8 * * * baz
30 * * * * plop
5 8 * * * bar
1 0 * * * foo
# End Whenever generated tasks for: project100

While you can human-parse this one easily, crontabs with several lines are hard …


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?…


RubyMine's clipboard can hold more than one string

By pressing Ctrl + Shift + V you can select a recently copied string for pasting.


Running a single unique instance of command + arguments

run-one is a wrapper script that won't run the given command while another instance of it is running. Is brings several utility commands that offer similar behavior.

run-one - run just one instance at a time of some command and unique set of arguments (useful for cronjobs, eg)

run-one COMMAND [ARGS]

   run-this-one COMMAND [ARGS]

   run-one-constantly COMMAND [ARGS]

   keep-one-running COMMAND [ARGS]

   run-one-until-success COMMAND [ARGS]

   run-one-until-failure COMMAND [ARGS]


Enumerators in Ruby

Starting with Ruby 1.9, most #each methods can be called without a block, and will return an enumerator. This is what allows you to do things like

  ['foo', 'bar', 'baz'].each.with_index.collect { |name, index| name * index }
  # -> ["", "bar", "bazbaz"]

If you write your own each method, it is useful to follow the same practice.

How to write a canonical each method

class MyCollection

def each(&block)
enumerator = do |yielder|
loop do
item = fetch…

External contentRepeats

Debugging AJAX requests with better_errors

better_errors is an awesome gem for enhanced error pages in development, featuring a live-REPL for some light debugging.

To debug the exception you got on an AJAX-Requests, visit /__better_errors on your app's root path (e.g. http://localhost:3000/__better_errors). It shows the error page for the last exception that occurred, even when it has been triggered by an AJAX request.


Haml: Prevent whitespace from being stripped in production


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 table:

  = link_to edit_admin_user_path(membership.user_id), class: 'btn' do
  = link_to admin_membership_path(membership), method: :delete, class: 'btn' do

In development you will see a small…

External content

Testing HTTPS with

Website that offers lots of different kinds of HTTPS configurations, bad or good or complicated.

They also offer a dashboard to check if your browser's HTTPS handling works as expected (which might be compromised e.g. due to security products or enterprise proxy servers).

External contentRepeats

Why Using the Greedy .* in Regular Expressions Is Almost Never What You Actually Want – Marius Schulz

Explains the difference betwen .* and .*?, and why the latter can lead to faster patterns.

VCR: Inspecting a request

Using VCR to record communication with remote APIs is a great way to stub requests in tests. However, you may still want to look at the request data like the payload your application sent.

Using WebMock, this is simple: Make your request (which will record/play a VCR cassette), then ask WebMock about it:

expect(WebMock).to have_requested(:post, '').with(body: 'yolo')

Easy peasy.

3267 cards