Caching in Rails

The information in this card is only relevant for Rails 2.3-era apps.


This note gives a quick introduction into caching methods (page caching, action caching and fragment caching) in rails and describes some specific problems and solutions.

The descriptions below are valid for Rails 2 and 3. Recently, caching with timestamp- or content-based keys has become more popular which saves you the pain of invalidating stale caches.

How to enable/disable caching

To enable or disable caching in rails you ca...

When using "render :text", set a content type

When your Rails controller action responds with only a simple text, render text: 'Hello' may not be what you want. You should not even use it on Rails 4.1+ any more.

By default, a "text" response from a Rails controller will still be a sent as text/html:

render text: 'Hello'
response.body # => "Hello"
response.content_type # => "text/html"

While this may not be too relevant for a Browser client, the response's content type is simply wrong if you want to send a plain-text response, and can cause trouble. \
For example, con...

Get the last leaf of a DOM tree (while considering text nodes)

I use this to simulate the (non-existing) :last-letter CSS pseudoclass, e. g. to insert a tombstone at the end of an article:

findLastLeaf = ($container) ->
  $children = $container.children()
  if $children.length == 0
    $container
  else
    $lastChild = $children.last()
    $lastContent = $container.contents().filter(->
      # Only return nodes that are either elements or non-empty text nodes
      @nodeType == 1 || (@nodeType == 3 && _.strip(@nodeValue) != '')
    ).last()
...

Chrome 34+, Firefox 38+, IE11+ ignore autocomplete=off

Since version 34, Chromium/Chrome ignores the autocomplete="off" attribute on forms or input fields. Recent versions of other browser do the same, although implementation details vary.

This is especially problematic for admin areas because Chrome might automatically fill in a password on a "add new user" forms.

Chrome developers say this is by design as they believe it encourages users to store more complex passwords.

Recommended fix for Chrome and F...

About "unexpected '#' after 'DESCENDANT_SELECTOR' (Nokogiri::CSS::SyntaxError)"

The error unexpected 'x' after 'DESCENDANT_SELECTOR' (Nokogiri::CSS::SyntaxError) (where x may be basically any character) occurs when the Nokogiri parser receives an invalid selector like .field_with_errors # or td <strong>.

In Cucumber, the culprit will be an invalid step definition that builds an invalid selector:

# inside some step definition:
field = find_field(label)
page.send(expectation, have_css(".field_with_errors ##{field[:id]}"))

The above raises the mentioned error if field[:id] is nil, i.e. the foun...

YAML: Keys like "yes" or "no" evaluate to true and false

If you parse this Yaml ...

yes: 'Totally'
no: 'Nope'

... you get this Ruby hash:

{ true: 'Totally',
  false: 'Nope' }

In order to use the strings 'yes' and 'no' as keys, you need to wrap them with quotes:

'yes': 'Totally'
'no': 'Nope'

There's actually a long list of reserved words with this behavior:

y|Y|yes|Yes|YES|n|N|no|No|NO
|true|True|TRUE|false|False|FALSE
|on|On|ON|off|Off|OFF

I'm sorry.

OpenStack nova resize "ERROR: Resize requires a change in size"

If you get this error when you try to resize an OpenStack instance:

# nova resize example 23 --poll
ERROR: Resize requires a change in size. (HTTP 400)

You need to change your flavor to have a different memory size. It's a bug in an older OpenStack version:

        # /nova/compute/api.py
        if (current_memory_mb == new_memory_mb) and flavor_id:		
            raise exception.CannotResizeToSameSize()

which got fixed 2012-09-12 ([https://git.openstack.org/cgit/openstack/nova/commit/nova/compute/api.p...

Making media queries work in IE8 and below

When using @media CSS queries, Internet Explorer 8 and below will fail to respect them.

Though there are several options (like mediatizr and css3-mediaqueries), Respond.js was the only one that worked for me.


If you do not want to pollute your application's default JS file with Respond.js, simply:

  1. Create an extra JS file (like media_queries_polyfill.js) that loads Respond.js:

    //= require respond-1.4.2
    
  2. Make sure it's added to config.assets.precompile

  3. Embed that JS fi...

Spreewald: Old-school cucumber steps, freshly pickled

Cucumber_rails' old-school web-steps have been deprecated for a while, urging developers to write high-level step definitions that directly use Capybara or Webrat.

We think that's a bit drastic. More high-level steps are good, but ticking the odd check box with a general step is not always bad.

So we took the old web steps, improved them a bit, added some other favorites of ours (steps for emails, tables, [time travelling](/ma...

Disabling HSTS

If you once had HTTP Strict Transport Security enabled for a domain, and you want to disable it again, you need to send this header over a secure connection:

Strict-Transport-Security: max-age=0;

The next time a browser visits your site, it will forget that it was once flagged as HTTPS-only.

Should you need to remove the HSTS flag from your local browser (e.g. for debugging), you can do so in Chrome by accessing [chrome://net-internals/#hsts](chrome://net-internals/#hs...

Retrieving the class an ActiveRecord scope is based on

Edge Rider gives your relations a method #origin_class that returns the class the relation is based on.
This is useful e.g. to perform unscoped record look-up.

Post.recent.origin_class
# => Post

Note that #origin_class it roughly equivalent to the blockless form of #unscoped from Rails 3.2+, but it works consistently across all Rails versions. #unscoped does not exist for Rails 2 and is broken in Rails 3.0.

Disabling Spring when debugging

Spring is a Rails application preloader. When debugging e.g. the rails gem, you'll be wondering why your raise, puts or debugger debugging statements have no effect. That's because Spring preloads and caches your application once and all consecutive calls to it will not see any changes in your debugged gem.

Howto

Disable spring with export DISABLE_SPRING=1 in your terminal. That will keep Spring at bay in that terminal session.

In Ruby, [you can only write environment variables that subproc...

How to create Rails Generators (Rails 3 and above)

General

Programatically invoke Rails generators
: Require the generator, instantiate it and invoke it (because generators are Thor::Groups, you need to invoke them with invoke_all). Example:

    require 'generators/wheelie/haml/haml_generator'
    Generators::HamlGenerator.new('argument').invoke_all

Other ways: Rails invokes its generators with Rails::Generators.invoke ARGV.shift, ARGV. From inside a Rails generator, you may call the [inherited Thor method invoke(args=[], options={}, config={})](https://github....

Ruby Exception Class Hierarchy

This note summarizes the ruby exception hierarchy.

Exception
  NoMemoryError
  ScriptError
    LoadError
    NotImplementedError
    SyntaxError
  SignalException
    Interrupt
      Timeout::Error    # < ruby 1.9.2
  StandardError         # caught by rescue (default if no type was specified)
    ArgumentError
    IOError
      EOFError
    IndexError
    LocalJumpError
    NameError
      NoMethodError
    Ran...

Sticky table header with jQuery

When you want the table headers to always stay around (e.g. because that table is huuuge), use the code below.

Style

table.fixed_table_header{
  position: fixed;
  top: 0;
  width: auto;
  display: none;
  border: none;
  margin: 0;
}

Javascript

;(function($) {
   $.fn.fixHeader = function() {
      return this.each(function() {
         var $table = $(this),
            $t_fixed;

         function init() {
            $t_fixed = $table.clone();
            $t_fixed.find('tbody').remove().end().addClass('fi...

Hash any Ruby object into an RGB color

If you want to label things with a color but don't actually care which cholor, you can use the attached Colorizer class.

To get a completely random color (some of which will clash with your design):

Colorizer.colorize(some_object) # => "#bb4faa"

To get similiar colors (e. g. bright, pale colors of different hues):

 # random hue, saturation of 0.5, lightness of 0.6
Colorizer.colorize_similarly(some_object, 0.5, 0.6) # => "#bbaaaa"

Also see the color gem.