route_downcaser 1.1.5 – compatible with Rails 5.0

The Rails community released Rails 5.0.0.beta1 just before christmas. I’ve added this release to route_downcaser’s test-suite for version 1.1.5, and I’m happy to say, that everything works out of the box. So unless something substantially changes in Rails (which ought not happen), then there will be no problems with upgrading to Rails 5.0 – at least with regards to route_downcaser.

More info about the gem here:

Automatic change RVM environment when switching Git branch

I use RVM all the time when I develop Ruby (and Rails) applications. It’s great for isolating Ruby environments and gem packages for a specific project. I also use git extensively – especially branching when developing new features for an app.

Sometimes a branch works with new gems, that I do not want to pollute my main project-specific gemset with. So I create a new RVM gemset for this particularly branch. This has had its own problems because a “git checkout” now also needed to be followed by a “rvm use” statement. Also having a .ruby-gemset file in the project root led to RVM resetting the current gemset as soon as I changed directory.

One solution could be to check-in the .ruby-version/.ruby-gemset files in each branch, but I don’t want to annoy fellow developers with my RVM files. So I came up with the solution below instead.

First for this example, I assume that you have a git repository containing a master branch and another branch. If not, here’s a quickstart to make this happen:

$ mkdir myproject && cd myproject

$ git init .

$ touch 1.txt

$ git add -A

$ git commit -m 'First master commit'
[master (root-commit) b578056] First master commit
 2 files changed, 2 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 1.txt

$ git checkout -b somebranch
Switched to a new branch 'somebranch'

$ touch 2.txt

$ git add -A

$ git commit -m 'First somebranch commit'
[somebranch d10e2c1] First somebranch commit
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 2.txt

$ git checkout master
Switched to branch 'master'

$ git branch
* master

Okay with that squared away, let’s get on with the actual steps. You need to create a RVM gemset for each branch (master and somebranch) with the appropiate .ruby-version/.ruby-gemset files. The principle is, that you rename them, so they have a postfix named after the branch.

First create for the master branch:

$ rvm --create --ruby-version 2.0.0@myproject-master
ruby-2.0.0-p643 - #gemset created /home/carsten/.rvm/gems/ruby-2.0.0-p643@myproject-master
ruby-2.0.0-p643 - #generating myproject-master wrappers..........

$ ls -a
.  ..  .git  .ruby-gemset  .ruby-version

Then rename the files:

$ mv .ruby-gemset .ruby-gemset-master
$ mv .ruby-version .ruby-version-master

$ ls -a
.  ..  .git  .ruby-gemset-master  .ruby-version-master

Now do the same for the branch “somebranch”:

$ rvm --create --ruby-version 2.0.0@myproject-somebranch
ruby-2.0.0-p643 - #gemset created /home/carsten/.rvm/gems/ruby-2.0.0-p643@myproject-somebranch
ruby-2.0.0-p643 - #generating myproject-somebranch wrappers..........

$ ls -a
.  ..  .git  .ruby-gemset  .ruby-gemset-master  .ruby-version  .ruby-version-master

$ mv .ruby-version .ruby-version-somebranch
$ mv .ruby-gemset .ruby-gemset-somebranch

Since the files are renamed as shown, they will not by themselves trigger an RVM gemset switch, if you enter the directory.

If you look at your git repo now, you will see the files as untracked.

$ git status
On branch master
Untracked files:
  (use "git add ..." to include in what will be committed)


nothing added to commit but untracked files present (use "git add" to track)

As stated in the beginning, we don’t want these files in the repository, so create a .gitignore file and add this:



Now comes the fun part. We are going to make a hook in our git config. Create this file



# Find current branch name
BRANCH=`git rev-parse --abbrev-ref HEAD`

# Copy branch-specific RVM files, if available - default to master-branch
if [ -f .ruby-gemset-$BRANCH ];
  cp -f .ruby-gemset-$BRANCH .ruby-gemset
  cp -f .ruby-gemset-master .ruby-gemset

if [ -f .ruby-version-$BRANCH ];
  cp -f .ruby-version-$BRANCH .ruby-version
  cp -f .ruby-version-master .ruby-version

And make sure, that the file is executable, since it is just a script:

chmod +x .git/hooks/post-checkout

After you have done this, everytime you checkout a branch, this script will be called. If you checkout somebranch, it will look for a .ruby-version-somebranch and .ruby-gemset-somebranch and copy them to .ruby-version and .ruby-gemset respectively. If you create a new branch but do not make a specific gemset for this branch, the script will instead copy .ruby-version-master/.ruby-gemset-master. So always as a minimum create these.

You might think that now you a all done. However if you try to checkout a “somebranch” now, things will seem strange. The .ruby-gemset file will be an exact copy of .ruby-gemset-somebranch, but if you call “rvm current”, you will still be on the master gemset. Why is this so?

The thing is: .ruby-gemset is now placed correctly, but will not be read by RVM until you change into the actual directory. Try this:

$ git checkout somebranch 
Switched to branch 'somebranch'

$ rvm current
ruby-2.0.0-p643@myproject-master      <== Not what we expected

$ cd .

$ rvm current
ruby-2.0.0-p643@myproject-somebranch  <== Much better

But this is still an extra manual step, that complicates things. You WILL forget this at some point, so let's get rid of it.

You need to edit your $HOME/.bashrc file and add this line:


git () { /usr/bin/git "$@"; cd .; }

This changes the git command to a function, which calls the executable git in /usr/bin with all arguments, and afterwards does the otherwise harmless "cd ." which will then make RVM reload the .ruby-version/.ruby-gemset files.

Exit the shell and open a new to reload .bashrc, and you're good to go.

Please let me know, if you have any trouble with the above. Everything has been tested, but evil typos may have creeped into the text.

Have fun!

Make testing possible with Rails and PostGIS

Inspired by this SO question:

I’ve had a lot of trouble recently with Rails and PostGIS. One of the main problem arised with testing. When you run Rails tests (or RSpec for that matter) the test database is always dropped and a new is created. The problem with this is, that the PostGIS extension is not created in this new database. Therefore your schema-load will fail, if you have any postgis-specific fields/indices.

The solution to this is to use a PostgreSQL database template – and of course the activerecord-postgis-adapter found here:

First the template:

You need a PostgreSQL template with PostGIS functions support.

Create a template database:

$ psql -U postgres
> CREATE DATABASE template_postgis WITH TEMPLATE=template1 ENCODING='UTF8';
> \c template_postgis;

Load necessary PostGIS functions into template (your SQL files may be located in a different path, but they come with the PostGIS installation):

$ psql -U postgres -f  /usr/share/postgresql/9.1/contrib/postgis-2.1/postgis.sql template_postgis
$ psql -U postgres -f /usr/share/postgresql/9.1/contrib/postgis-2.1/spatial_ref_sys.sql template_postgis
$ psql -U postgres -f  /usr/share/postgresql/9.1/contrib/postgis-2.1/topology.sql template_postgis

Set database as template and grant permissions:

$ psql -U postgres template_postgis
> UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template_postgis';
> GRANT ALL ON geometry_columns TO PUBLIC;
> GRANT ALL ON spatial_ref_sys TO PUBLIC;

Now the adapter:

Add this gem to your Gemfile and run bundle:

gem 'activerecord-postgis-adapter'

After that add the adapter and the template to your config/database.yml like this:

  adapter: postgis
  template: template_postgis
  database: mydb_development

  adapter: postgis
  template: template_postgis
  database: mydb_test

And that should do the trick! Test it by running rake db:schema:dump and rake db:test:prepare.

Let me know, if you get any additional problems regarding this.

Make Rails routing case insensitive with route_downcaser gem

A long time ago I solved a nagging issue concerning Rails’ handling of url casing (or rather: non-handling). I posted the resulting code here.

I’ve realised that a lot of people are actually using this solution, so I finally took the time to make it into a fully-tested gem.

The gem is released on RubyGems here.

All documentation (such as is needed) can be found on the gem’s github page.

All you actually need to do is adding the gem to your gemfile, run bundle, and the gem takes care of the rest. No config or initialization code needed, it’s all baked into the gem.

Enjoy! 🙂

Designing with Compass – my new best friend with mobile applications

Ruby on Rails has always been marketed as “Webdevelopment that doesn’t hurt”, and a lot of this comes from standing on the shoulders of giants.

One of the more recent pair of shoulders to pop up is Compass. I would say that Compass is a natural development, stemming from Haml and Sass. It has made stylesheet a more natural part of Rails application development.

While a lot of tools exists for creating “html-generated applications”, stylesheets have always been left a bit in the cold. Sass helped a bit by adding variables and partials, but it still didn’t feel like programming.

Compass adds two important things:

  • mixins which enables you to create behaviors that you apply to several css classes.
  • functions which can be used to generate css values based on parameters

To show why this is great, here’s an example of doing grid layout the Right Way(tm) – and The-Way-You-Used-To-Do-It…

Grid layouts is usually coupled with frameworks like Blueprint, 960 and others. One of the problems with this is, that you do not get semantic markup in your HTML. Instead you get all kinds of layout classes. Here’s an simple example of a typical Blueprint HTML layout:

      ...a lot of content...
      ... links etc. in the sidebar...

and in HTML for those of you who have not tried Haml yet (you really should):

...a lot of content...
... links etc. in the sidebar...
</body> </html>

Why is this bad? Well if you are only developing for traditional computers, you’re fine. But what if you want to use the same webapplication for Android or iOS devices? HTML5 has a nifty feature for stylesheet selection based on the clients screen size:


This is pretty cool – but then all the span-classes from our Blueprint example suddenly gets out of context.

Now back to why Compass is cool

Compass makes grid-design easy without using anything but your semantic markup. Here’s the same layout done with compass (again in Haml and HTML) – explanations can be found on Compass’ homepage.

  ...stylesheet inclusion...
      ...a lot of content...
      ... links etc. in the sidebar...
<head>  ...stylesheet inclusion...</head>
...a lot of content...
... links etc. in the sidebar...
</body> </html>

IMHO much prettier – and much easier to mould with different stylesheets. Here’s what it takes in Compass using mixins and functions:

@import "compass"

$blueprint_grid_columns: 24;
$blueprint_grid_width: 40px;
@import "blueprint"


  +column(6, true)

Now if you have a 320px device (phone) you could switch to a much simpler stylesheet – without worrying about any layout-specific HTML markup.

Avoid html escaping I18n strings in Rails 3

Update: Be careful with this method, if you have string-interpolation with user input. It might be the cause of XSS. I’ll cough up a better method, that can handle cases with and without interpolation

With Rails 3 comes a shift in who is responsible for escaping output. You no longer need to write <%= h(@some_value)%>, Rails will automatically escape every string unless you mark it html-safe.

Unfortunately this also goes for I18n strings. In my case I have a lot of strings containing HTML entities like &oslash; which is now escaped by Rails when I write <%=t(:some_key)%> and therefore “Søg” is now displayed as “S&oslash;g”. Not good.

A tiny fix for this:

module I18n
  class << self
    alias :prev_translate :translate
    def translate(*args)

This ensures that I18n output is marked as html-safe. Just place it as a initializer and your translations will work as before.

Trouble with Net::HTTP in Ruby 1.8.7 (released with Ubuntu 10.04)

I stumbled upon an error trying to work with acts_as_solr just after upgrading to Ubuntu 10.04. When trying to start the solr-daemon with

rake solr:start

i suddenly got an error not seen before:

undefined method `closed?' for nil:NilClass
/usr/lib/ruby/1.8/net/http.rb:1060:in `request'
/usr/lib/ruby/1.8/net/http.rb:962:in `request_head'

As the error hints, it’s something to do with the net/http library. After some googling I found out, that it is because Ubuntu 10.04 ships with Ruby 1.8.7, and that this particular version has a bug in the net/http library. Here’s the bug-report and the patch that will help:

Hopefully this patch will soon find its way to Canonical’s updates.

My favorite Apache setup for a Rails application

You think 1 site equals 1 Apache Virtual Host? Think again, and read on to figure out why not.

For every Rails application that I deploy into production mode, I usually creates 3 Virtual Host entries in Apache. To illustrate, here is the setup for our dog-site

Note: This setup is using Passenger (aka. mod_rails). If you are not already using it for your Rails production environment, you really should do so. It’s the best thing happened since Rails itself.


    DocumentRoot /var/www/rails/gipote_production/public

    RailsEnv production


    DocumentRoot /var/www/rails/gipote_production/public

    PassengerEnabled off

    ServerAlias *
    ServerAlias *

    RewriteEngine on
    RewriteRule ^(.*)$1 [R=301]

    PassengerEnabled off

The *=”” inside my virtual host declations is the WordPress SyntaxHighlighter playing tricks on me. It should just be an *

Some explanation is required…

First of all, I want one and only one entry into our site. This originally came from making it easier to setup Google Analytics (you need to tweak the tracking code to support multiple domains). But it seems that it also improves our SEO rankings – so more power to us.

So the first virtual host only accepts The last virtual host accepts all other variations on (except a few – I’ll come to that) as well as an entirely different domain The last virtual host redirects all these requests to

The last virtual host relly must be placed at the bottom, since it contains wildcards. These wildcards – * – will catch all hostnames not specified in any virtual host above it. Position is vital.

Now to the second virtual host. It requires a bit more explaining…

Internet Explorer and Firefox has a limit when fetching a webpage concerning concurrent connections to the same host. They will only have 2 open connections to a single host at a time. So if you have a page with many external files – or assets (css, js, images), you may find, that it is slow to load, even if you have a powerful server. The bottleneck is at the client this time.

Rails have a fix for this: Every asset specified in the ERB by the asset helpers image_tag(), stylesheet_link_tag(), etc. Can automatically prepend the URL with an asset host. You need to define the asset host in your config/environments/production.rb file:

config.action_controller.asset_host = ""

The %d is important. This will make Rails’ asset helpers prepend either of

to any asset url. It will use exactly these 4 variants, and they will be distributed (almost) evenly out on your assets.

So image_tag(‘logo.png’) will become (or 0, 1, 3).

The cool thing about this is, that the aforementioned browsers will open 2 connections for each host. So instead of fetching 2 assets concurrently, your browser will now fetch 8 at the same time.

So we need our Apache to deal with this. We cannot rely on the last virtual host to do this, because it will simply redirect to And we don’t want to add these 4 hostnames as alias’ to the top virtual host, because we don’t want our users to be able to access our Rails application by any other hostname than

So I create the second virtual host. Put in all 4 hostnames, point it to my Rails public folder. Oh – and for good performance measure, I disable Passenger (PassengerEnabled off). Otherwise the users would still be able to use the hostnames to access our application.

How to make Rails routing case-insensitive

Update 2013-01-06: I have now converted this into a gem: Read more

Update 2011-03-10: Brian Marquis pointed out, that I’ve missed showing a good way to actually load the .rb file containing the middleware. This has now been added to the article.

Update 2010-11-06: Rails 3 has changed its routing mechanism. One of the changes involves which environment variable is used as the source for routing. In Rails 2.3.x it was REQUEST_URI, in Rails 3 it is PATH_INFO. I have changed the middleware code to take care of both versions.

At our dog-site we have a shop selling dog-tags. The URL for this shop is (hundetegn = dog-tag in danish). However one of our marketing-guys have a tendency to capitalize the word “hundetegn”, so that URL reads (with a capital H).

Rails will yield a 404 NOT FOUND on this, simply because it is case sensitive. The Rails core team doesn’t seem to want this changed, but I found a neat way of doing it myself: Using the new Rack Middleware framework.

First the solution:

Create a file called downcase_route_middleware.rb and put it in RAILS_ROOT/lib or wherever you think middleware files ought to go. Fill it with this piece of code:

class DowncaseRouteMiddleware
  def initialize(app)
    @app = app

  def call(env)
    # Rails 2.3.x routing use REQUEST_URI
    uri_items = env['REQUEST_URI'].split('?')
    env['REQUEST_URI'] = uri_items.join('?')

    # Rails 3.x routing use PATH_INFO
    env['PATH_INFO'] = env['PATH_INFO'].downcase

Now to telling Rails to use this new middleware class. This differs a bit in Rails 2 and 3.

Adding the middleware in Rails 3.x:

Open config/application.rb and find the lines

module YourAppName
  class Application < Rails::Application
    ..bunch of code..

Add the middleware code like this:

module YourAppName
  class Application < Rails::Application
    config.autoload_paths << "#{config.root}/app/middleware"
    config.middleware.use "DowncaseRouteMiddleware"

    ..bunch of code..

Adding the middleware in Rails 2.3.x:

Open up config/environment.rb, and find the line do |config|

  ...a lot of config code...

Add the middleware code, so it looks like this afterwards do |config|
  config.autoload_paths << "#{config.root}/app/middleware"
  config.middleware.use "DowncaseRouteMiddleware"

  ...a lot of config code...

Update: The line:
config.autoload_paths << "#{config.root}/app/middleware"
is my general way of using middleware. I always places all my middleware classes in a folder called app/middleware. The line above enables Rails to automatically search the autoload-path for a file that matches the middleware class used (i.e. "downcase_route_middleware.rb").

If this is the only middleware class that you use, you can simply do a
require "downcase_route_middleware.rb""
somewhere in your config initializers. I just find the above solution more elegant.

Restart your rails application, and it will now accept all kinds of casing on the routing part.

Note: This code only downcases the part of the URI containing namespace, controller, action, and id. It does not touch the querystring parameters, and for a good reason too: The parameter values could contain some context in their casing.

Now for the explanation:

Rails 2.3 introduced Rack middleware. A lot of people have already explained this concept, so instead of going into details, I suggest that you read Pratik's explanation on Rails Guides and Ryan's Railscast on the subject.

Basically, my middleware class gets access to the environment hash and passes it on to the next middleware class on the stack. In between I get to modify the nessecary data. In this case it's the REQUEST_URI (In Rails 3 it's PATH_INFO), since ActionController::Dispatcher uses the URI from here to determine the correct route. By converting the URI to lowercase, ActionController::Dispatcher gets the correct path no matter the case entered by the user.

The woes of libodbc-ruby1.8 and Debian + Ubuntu

Update 05-05-2010: This issue still exists on the new Ubuntu 10.04 LTS (Lucid Lynx). The dist-upgrade will override any version locks that you have made on libodbc-ruby1.8 and install version 0.9997-2 (and lock it). So after a dist-upgrade you will have to remove libodbc-ruby1.8 and install the older version again.

I have the dubious honor of developing on a Rails application, that runs on top of Microsoft SQL Server. This has given some headaches at our most recent system upgrades.

My development machine runs Ubuntu 9.10 (Karmic Koala). Our servers run Debian 5.0 (Lenny).

If you run any of these OS versions and encounter an error like the following:

dbd-odbc-0.2.4/lib/dbd/odbc/driver.rb:36:in `connect':DBI::DatabaseError: INTERN (0) [RubyODBC]Cannot allocate SQLHENV

then help can be found here.

The problem on both OS’es lies in the package libodbc-ruby1.8. But it is actually stranger than you might expect, which I will explain below.

Ubuntu first

We’ll start off with Ubuntu. Fire up Synaptic Package Manger and search for libodbc-ruby1.8. You will see, that the distribution package is versioned 0.9997-2. You need to uninstall this and install version 0.9995-1 instead. You can download version 0.9995-1 here:

Now install it with apt-get and… problem solved. Please note however that your automatic package update will revert to version 0.9997-2 unless you uncheck it before running the update.

Update 19-02-2010: This is also an issue on the 64-bit version of Ubuntu 9.10. Here’s a link where you can download the 0.9995-1 .deb package for both 32-bit AND 64-bit. Thanks Goran.

Debian next

On Debian it’s the other way around. Debian comes installed with libodbc-ruby1.8 version 0.9995-1 and you need to upgrade this to 0.9997-2. This package is currently only found in unstable, but you can download it here:

Install it with apt-get, overriding the previous package.

Hope this saves you from the days of work that I invested in this particular oddity. 🙂