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:

Easy time-tracking when using Jira

I’ve made a small Windows* tool to make time-tracking with Jira much easier IMHO.

Jira StopWatch

Read more and get it here:

The use-case goes like this:

At work I’m usually working on up to 5 issues at a time – sometimes an issue is waiting for input from somebody temporarily away. Sometimes I need to prioritise a new issue above others. So I need to be able to quickly switch between issues – and still make sure to track how long I’ve totally worked on each issue.

So if you’re interested, take it for a spin, and let me know if you have any suggestions for improving it.

A short screencast to show the usage:

Jira StopWatch tutorial from Carsten Gehling on Vimeo.

* It’s OSS C# and also compiles with Mono on Linux – somebody with a Mac care to try?

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!

Reduce Linux boot-time by lazy-loading development-specific services

I’m very anal when it comes to boot time. When I power up my laptop, I want it to be available for me ASAP. As a developer this sometimes conflicts with the need of having a lot of daemons running: PostgreSQL, MySQL, Apache, Memcache, Redis, Solr, etc etc. Services that are needed when i work on different projects. All these daemons takes time to start up, and since I don’t always program, I don’t always need them. But still they start up, and still I have to wait.

So I solved this by disabling the services in the /etc/rc.* folders. And instead I made this little script, which I put into $HOME/bin (which of course is already in your $PATH, right?)


# Must run as root
if [ $(id -u) != "0" ]
    sudo "$0" "$@"
    exit $?

service apache2 $1
service postgresql $1
service mysql  $1

It automatically ask for your sudo password, and then either starts or stops your daemons depending on the parameter, that you supply.

Fancy Ruby stuff done in C#, part 3: dynamic properties

Please read this post for my reasons behind this article series.

Some people have asked me, why I try to do things in C# that are clearly Ruby-ideoms. The short answer is: Because I can. The longer answer involves thoughts about that you should never stop learning. For a programmer, this involves pushing your tools to their boundaries and beyond. Seeking new insights other places and apply them to your environment. Stuff like that.

Catch-all property (like Ruby’s method_missing)

One of the powerful features of Ruby is method_missing. With this seemingly innocent construct you are able to make a class respond to things that are not statically defined beforehand.

Typical uses are for ORMs like ActiveRecord, that enables you to map class properties to database table-fields without explicitly defining the fieldnames in your class.

The way ActiveRecord does this is, that the model base-class contains a Hash (Dictionary) called attr. When a table-record is loaded, all fields are loaded into this hash. And method_missing are then used to map property-names directly to keys in the hash.

user = User.find(13)

This can also be done in C# using DynamicObject.

DynamicObject is a rather bold introduction into a strong-typed language like C#, since it expose members such as properties and methods at run time, instead of at compile time.

using System;
using System.Collections.Generic;
using System.Dynamic;

public class MyFakeORM : DynamicObject {
    // For a clearer example, I don't go into the stuff about loading data from the database into this model

    // Dictionary to hold all fields from the loaded record
    Dictionary _attr = new Dictionary();

    // Catch-all methods for getting and setting a "missing" property
    public override bool TrySetMember(SetMemberBinder binder, object value) {
        _attr[binder.Name] = value;
        return true;

    public override bool TryGetMember(GetMemberBinder binder, out object result) {
        return _attr.TryGetValue(binder.Name, out result);

Note: For this to work, you also need to define your instance-variable as a dynamic instead of MyFakeORM:

dynamic user = new MyFakeORM(); = "";


If you want to enable access with both properties as shown above AND as a common Dictionary, you need to add setters and getters for the class:

using System;
using System.Collections.Generic;
using System.Dynamic;

public class MyFakeORM : DynamicObject {

    public object this[string key] {
        get {
            return _attr[key];
        set {
            _attr[key] = value;

    // The rest is as before

Now all of the following is valid:

dynamic user = new MyFakeORM(); = "";
user['email'] = "";


Fancy Ruby stuff done in C#, part 2: flash messages

Please read this post for my reasons behind this article series.

Using flash messages between web requests

Ok I admit, this is not entirely a C# vs. Ruby issue. It is more Ruby On Rails done with MVC3. But it uses some of the dynamic stuff from C#.

In Rails you can push messages between requests by using a special flash component:

controller UserController < ApplicationController

def Login
  user = (try-to-login-user)
  if not user.LoggedIn?
    flash[:error] = "Invalid credentials"
    redirect_to :controller => "LoginForm"

This will use sessions to carry the error-message into the next request. You can now test for the flash-message in LoginForm’s view:


<% if flash[:error] %>
  <div class="error"><%=flash[:error]%></div>
<% end %>

After this request, the flash message is erased automatically.

The same thing can be made in .NET by using a combination of the dictionary TempData” and C#’s extension methods. And we can formalize it a bit more by using an enum to control how many different message types, that we will accept.

Create a file called “FlashHelper.cs” with the following content:

using System;
using System.Collections.Generic;
using System.Text;

namespace System.Web.Mvc
    public enum FlashType

    public class FlashData
        public FlashType Key { get; set; }
        public string Message { get; set; }

    public static class FlashHelpers
        public static void Flash(this Controller controller, FlashType key, string message)
            if (controller.TempData["flash"] == null)
                controller.TempData["flash"] = new List<FlashData>();

            var flashList = controller.TempData["flash"] as List<FlashData>;
            flashList.Add(new FlashData {Key = key, Message = message});

        public static MvcHtmlString Flash(this HtmlHelper helper)
            var sb = new StringBuilder();

            if (helper.ViewContext.TempData["flash"] != null)
                foreach (FlashData flash in helper.ViewContext.TempData["flash"] as List<FlashData>)
                    sb.AppendLine(string.Format("<div class=\"flash {0}\">", flash.Key.ToString().ToLower()));
            return MvcHtmlString.Create(sb.ToString());

What I am doing here is, that I extend the base MVC controller with a new method called “Flash()”. You call this in your controller to set a new message, supplying the type of message and the message-string itself.

The same goes for extending the Html helper. I define a method, that will print out all added messages, each of them wrapped into their own DIV tag with classes set appropiate of the message type.

So now we can write a C# MVC 3 example like the Rails one above.

The controller:

public class UserController : Controller
  public RedirectToRouteResult DoLogin(string username, string password)
    var user = (try-to-login-user);

    if (!user.LoggedIn()) {
      this.Flash(FlashType.Error, "Invalid credentials");
      return RedirectToAction("LoginForm");

And in your _layout.cshtml view:

@Html.Flash() @RenderBody()

If this example is run, and the user tries to login with invalid credentials, the @Html.Flash() call will render:

<section id="main">
    <div class="flash error">Invalid credentials</div>

which you can then style with CSS.

Fancy Ruby stuff done in C#, part 1: extension methods

Ruby is a very dynamic language, and you are able to do a lot of stuff with class extensions, meta programming, lambda functions and so forth. When I first experienced Ruby back in 2006 I was very impressed with some of the stuff possible – things that IMHO made C# look stale and static.

Not so any more. The recent updates to C# in 2008 (with .NET 3.5) and lately with .NET 4.0 has added functionality, that enables a more dynamic approach to C# programming, while still keeping the safety net of a strongly typed compiled language.

This is the first part of a small series, where I will take some of the goodies from Ruby and explain how to do it in C#.

Extending classes without subclassing

Most people a first exposed to Ruby through the web framework Ruby on Rails (Rails for short). Rails does a number of cool tricks. One of them is in the ActiveSupport part where the Integer class is extended with some extra methods called days(), weeks(), months(), and years(). This enables some “wow” effects when first looking at Rails code. You are able to do stuff like this:

short_period = 10.days
  => returns a Fixnum with value 864.000 (10 days in seconds)

  => returns the string "10 days"

long_period = 3.weeks
  => returns a Fixnum with value 1.814.400 (21 days in seconds)

And even create dates like this

realistic_deadline = 2.weeks.from_now

original_deadline = 5.days.ago

Doing this in C#

This stuff is not originally built into Ruby. The authors of Rails extended the Fixnum class with methods these methods. This is also doable in C#:

public static class IntegerExtensions
    public static Days Days(this int days)
        { return new Days(days); }
    public static Weeks Weeks(this int weeks)
        { return new Weeks(weeks); }
    public static Months Months(this int months)
        { return new Months(months); }

This introduces 3 new classes, that I will create now:

public class Days
    private int days;

    public Days(int d)
        { days = d; }

    public override string ToString()
        { return string.Format("{0} days", days); }

    public DateTime Ago()
        { return DateTime.Today.AddDays(-days); }

    public DateTime FromNow()
        { return DateTime.Today.AddDays(days); }

public class Weeks
    private int weeks;

    public Weeks(int w)
        { weeks = w; }

    public override string ToString()
        { return string.Format("{0} weeks", weeks); }

    public DateTime Ago()
        { return DateTime.Today.AddDays(-7 * weeks); }

    public DateTime FromNow()
        { return DateTime.Today.AddDays(7 * weeks); }

public class Months
    private int months;

    public Months(int m)
        { months = m; }

    public override string ToString()
        { return string.Format("{0} months", months); }

    public DateTime Ago()
        { return DateTime.Today.AddMonths(-months); }

    public DateTime FromNow()
        { return DateTime.Today.AddMonths(months); }

With these into place I can do this

Console.WriteLine("{0}", 10.Days().Ago());
Console.WriteLine("{0}", 10.Days().FromNow());

DateTime originalDeadline = 2.Weeks().Ago();

DateTime realisticDeadline = 3.Months().FromNow();

Pretty neat, huh? If only we could loose the parantheses when calling the methods, but I guess we can’t have all. ūüôā

Continue to part 2.

Vil du outsource? De 3 vigtigste råd

Gennem mine 8 år som selvstændig, har jeg gjort en dyd ud af, at bruge eksterne eksperter. Både på de områder, hvor jeg ikke selv havde kompetencer, men også indenfor mine egne områder, hvis der var for meget at lave. I de sidste 3 år brugte jeg meget folk fra udlandet: Bulgarien, Ukraine og Indonesien. Det har både været godt, men jeg har også brændt fingrene.

Derfor giver jeg her de 3 vigtigste erfaringer, som jeg har gjort mig:

1. Ans√¶t dine programm√łrer for en l√¶ngere periode af gangen

Du skal ikke hyre teams for enkelte projekter (f.eks. programmering af en hjemmeside). Alt for ofte vil du opleve √¶ndringer i projektets krav undervejs, og s√• kan du nemt komme til at st√• i en klemme. Leverand√łrerne kan desv√¶rre vise sig meget ufleksible med at afvige fra det aftalte.

Det er meget bedre at ans√¶tte en eller flere programm√łrer, som du s√• har fuld r√•deret over. Tro mig – du vil altid have noget, som de kan lave… ūüôā P√• den m√•de er du ikke n√¶r s√• s√•rbar overfor √¶ndringer i projekter.

2. S√łrg altid for at du ogs√• f√•r kildemateriale

Uanset om du f√•r produceret en flashfilm, et design eller et program, s√• skal du udover det f√¶rdige produkt ogs√• f√• en kopi af kildematerialet. Ogs√• selvom du ikke selv har viden til at bruge den. Hvis du ikke g√łr, s√• har du bundet dig til leverand√łren.

Jeg har oplevet, at en leverand√łr skulle lave nogle vigtige √¶ndringer i en flash film 1¬Ĺ m√•ned efter at projektet var f√¶rdigt. Men de havde pludselig ikke l√¶ngere tid, fordi de havde f√•et nogle store opgaver ind fra andre (vigtigere) kunder. Jeg kunne derfor v√¶lge at vente 2 m√•neder eller f√• lavet flash-filmen helt forfra et andet sted. Ikke s√• fedt…

3. Outsourcing er ikke s√• effektivt som “lokalt ansatte”

Du skal regne med langt mere overhead og projektadministration, end hvis du havde dine folk ansat i samme kontor som du sidder i. Dels er det sv√¶rere at kommunikere p√• engelsk – ikke mindst fordi, at leverand√łrerne ikke altid er super-gode til engelsk. Men simpelthen ogs√• fordi man mangler muligheden for at st√• samlet om en white-board tavle og “tegne-fort√¶lle”. Der findes mange gode kommunikationsv√¶rkt√łjer p√• nettet, men det bliver bare aldrig helt det samme.

Tommelfingerregel: Et projektteam i udlandet har en effektivitet p√• ca. 50% af et, der sidder sammen med dig. V√¶r forberedt p√•, at ting skal forklares igen og igen og med mange eksempler, f√łr det er helt forst√•et. Forvent, at ting skal kodes om 2-3 gange, inden den sidder i skabet.

V√¶r opm√¶rksom p√•, at du kommer til at bruge meget tid p√• at koordinere projekterne. Du f√•r derfor ikke noget reelt udbytte af kun at hyre en programm√łr.

Det lyder besværligt Рskal jeg helt lade være?

Det er sv√¶rt at svare entydigt p√•. Du skal i hvert fald ikke lade dig lokke bare af en billig pris. Til hyrede vi en Rails programm√łr i Indonesien for 3 m√•neder af gangen. Vi havde nogle helt konkrete opgaver til ham. Dem l√łste han ogs√• rimelig godt, men til geng√¶ld brugte jeg en del tid p√• at s√¶tte ham ind i opgaverne og kontrollere dem bagefter. Dermed blev min egen produktivitet s√¶nket. Det var f√łrst, da vi ansatte endnu en programm√łr, at det virkelig gav noget. Vi brugte et firma, der hedder Kiranatama til Rails udvikling – dem kan jeg bestemt anbefale og jeg ville selv bruge dem igen

Og s√• lige en sidste ting: Hvis du selv er et en-mands firma, s√• har du nok ligesom jeg en st√¶rk holdning til, hvordan tingene skal g√łres – “my way or the highway”. Det skal du l√¶re dig selv at l√¶gge p√• hylden. For det kode, du f√•r hjem, ligner med garanti ikke noget, som du selv ville lave. Men det kan du nok ogs√• l√¶re noget af – det gjorde jeg. ūüôā

What to learn next?

I’ve always had principle to learn at least one new technology/programming language/framework every year. So far it has, among the most interesting, amounted to: C and C++, Pascal, Delphi, Foxpro, MySQL (and developing on the MyODBC driver), Informix, Oracle, MSSQL, ASP, PHP, Perl, Python, Zope/Plone, Typo3, Drupal, OO Patterns, SCRUM project methods, Ruby on Rails, Prototype, … I’ve probably missed some.

This doesn’t mean, that I still use all of the above – simply that I always strive to learn something new, evaluate it, and maybe continue to use it.

I am in no way finished with Ruby on Rails – especially since this has become basis for my new full-time job. But I would really feel like stalling, if I don’t try something new.

So what do I really need to look at next? We are coming to the end of 2008 – what does 2009 have to offer my curiosity?