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.

Restangular: How to remove an element from a collection without breaking restangular

So you have a restangular collection and you want to remove an element from it, after you've successfully deleted it from the server.

The README suggests to say something like $scope.users = _.without($scope.users, user). While that works at first glance (the element is no longer in your collection), it will break horribly when you want to use restangular's attributes on that collection.

This...

better rails app restart with the passenger restart-app tool

With this command you can initiate an application restart without touching restart.txt. Unlike touching restart.txt, this tool initiates the restart immediately instead of on the next request. http://blog.phusion.nl/2014/01/02/phusion-passenger-4-0-33-released/

If you want to use this with capistrano 2.x just replace the touch command:

-    run "touch #{current_path}/tmp/restart.txt"
+    run "passenger-config restart-app --ignore-app-not-running #{deploy_to}...

Rails 2: Refuse response formats application-wide

If you regularly get ActionView::MissingTemplate exceptions, maybe some bot visits your site requesting silly formats like:

http://www.rails-app.com/makandra.html-username-2000 # => Rails tries to retrieve 'makandra' with format 'html-username-2000'

Just restrict accepted format parameters for the whole application like this:

class ApplicationController < ActionController::Base

  before_filter :refuse_silly_formats

  private

  def refuse_silly_formats
    acceptable_formats = %w[html xml pdf]

    if par...

AngularJS directive to format a text with paragraphs and new lines

If you are using Angular and want something like Rails' simple_format which HTML-formats a plain-text input into paragraphs and line breaks, this directive is for you.

Any HTML fragments inside that text will still be escaped properly.

Use it like this, where your text attribute specifies something available in your current scope:

<simple-format text="email.message"></simple-format>

This is the directive, in CoffeeScript syntax:

@app.directive 'simpleFor...