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! 🙂

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)
puts user.email

This can also be done in C# using DynamicObject. http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx

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();

user.email = "carsten@sarum.dk";

Console.WriteLine(user.email);

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 = "carsten@sarum.dk";
user['email'] = "carsten@sarum.dk";

Console.WriteLine(user.email);
Console.WriteLine(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"
  end
end
...

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:

<h1>Login</h1>

<% 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
    {
            Info,
            Warning,
            Error
    }

    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()));
                    sb.AppendLine(flash.Message);
                    sb.AppendLine("</div>");
                }
            }
            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>
    ...
</section>

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)

10.days.to_s
  => 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(10.Days().ToString());
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.

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:

!!!
%head
%body
  .container
    .main.span-18
      ...a lot of content...
    .sideinfo.span-6.last
      ... links etc. in the sidebar...

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

<html>
<head></head>
<body>
  
...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:



etc...

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.

!!!
%head
  ...stylesheet inclusion...
%body
  .container
    .main
      ...a lot of content...
    .sideinfo
      ... links etc. in the sidebar...
<html>
<head>  ...stylesheet inclusion...</head>
<body>
  
...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"

.main
  +column(18)

.sideinfo
  +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.

Learn how to program

You’re exited about computers, and would like to do more than just surf the web and play games? Then you are ready to start programming!

But how do you go about learning this?

There are a number of good guides on the web, that you can follow. Here are links to those, that I find especially good for absolute beginners:

CodeAcademy

http://www.codecademy.com

This is a fully online interactive tutorial, that will teach you the basics of Javascript. Everything happens in a frame on the site, and you will get instant visual feedback – very important for you when just starting up. So go on and get your hands dirty on CodeAcademy, and then get back here for the next guide.

The guide will teach you the basics of a programming language called JavaScript. Most of the dynamic interaction that you see on sites like Facebook (popup boxes and such) are made using Javascript. It is the only language, that every browser understands and can execute within a web page. However, you will hardly use JavaScript to anything else than this, so if you want to go on programming stuff to run on your computer, you will need to look for another programming language.

There are many to choose from. Some are suited for special purposes, others are more general. Luckily a lot of the features, that you have already learned in the first guide, are shared between many programs, such as “if” and “while” statements.

TryRuby

http://tryruby.org

This next guide will introduce you to Ruby, a general-purpose programming language, with which you will be able to go a long way. Just like the first guide, this is an interactive tutorial using a console on the screen. Enough said – go on and try it.

Install ruby on your own computer

Ok now you’ve been programming online on a webpage, so now it is time to do things on your own computer as well.

You need to install the Ruby Programming Language before you can do anything else. Luckily this is easy: Go to this website and follow the instructions. http://rubyinstaller.org

You will also need a good text-editor. Notepad simply doesn’t cut it. But you are in luck – the RubyInstaller also contains a good editor called SciTE. This is actually all that you need.

Now you are ready to start programming on your own computer. Go through this guide, which will also move you from the interactive prompt, that you’ve been familiarized with in the other guides, and onto creating text-files containing your progam.

http://www.ruby-lang.org/en/documentation/quickstart

Good luck! Let me know if you have any hardships, and I will gladly help you.

Nye muligheder for outsourcing og joint-ventures i Bangladesh

I slutningen af januar var jeg pĂĄ rejse til Bangladesh, hvor jeg deltog pĂĄ en IT-messe i hovedstaden Dhaka. Anledningen var som medlem af en delegation sammensat af HĂĄndværkerrĂĄdet og ITC, som ønskede at undersøge mulighederne i og niveauet for Bangladesh’ IT-branche. Delegationen bestod af repræsentanter fra danske og hollandske virksomheder.

Arrangementet var fantastisk godt sammensat af ITC (thank you Martin Labbé). På messeområdet havde ITC arrangeret et lokale, hvor vi kunne sidde i ro og fred og mødes med en række virksomheder, som vi havde udvalgt på forhånd udfra et stort virksomhedsindeks. Efterfølgende var vi på besøg hos så mange af virksomhederne som muligt.

Nogle af de interessante og positive observationer, som vi gjorde var:

  • Bengalerne er meget stolte og bevidste om deres evner. De mødte os i øjenhøjde som ligemænd og ikke som “underdanige”.
  • De er utrolig godt forberedte til møderne, de kom gerne 2 eller 3 repræsentanter fra samme firma, og alle kunne bidrage til samtalen.
  • Meget motiverede, engagerede ambitiøse og visionære.
  • Højt uddannelsesniveau og gode tekniske evner.
  • Generelt god ledelse.
  • Mange af virksomhederne har ejere/ledere, der har boet en ĂĄrrække i EU eller USA. Der har de taget en formel uddannelse og fĂĄet erhvervserfaring, inden de er rejst hjem for at starte egen virksomhed i Bangladesh.
  • Viser tydelige evner for at kunne tage halvfærdige idĂ©er og selv have den nødvendige innovation til at kunne færdiggøre dem til komplette løsninger.

Bangladesh er interessant for danske virksomheder i øjeblikket. Det er nemlig muligt i øjeblikket at søge om Danida støtte, hvis man som dansk virksomhed er villig til at starte et joint-venture op sammen med en eksisterende lokal virksomhed. Flere har allerede gjort det med succes, men hvis det skal være et joint-venture, hvor den lokale partner bidrager konstruktivt, så er der brug for en ligeværdig partner med et højt niveau af selvstændighed, visioner og innovation.

Og det finder man i Bangladesh.

Endelig! Kortlægning af dansk erhvervsliv

SĂĄ blev vi endelig færdige med vores nye killer-funktion “Six degrees of separation” indenfor dansk erhvervsliv. Prøv den selv.

F.eks. kan min far nu prale af, at han kender Mærsk McKinney Møller.

Med over 1.9 millioner personrelationer at gennemsøge, var det lidt af en udfordring, ikke mindst fordi servicen gerne skulle svare lynhurtigt uanset hvor mange, der nu besøger den. SQL var udelukket – databasen simpelthen for langsom. Men data skulle centraliseres, sĂĄ flere processer kunne fĂĄ adgang til dem samtidig. Løsningen blev Redis og en lynhurtig algoritme i Ruby.


Har du prøvet den sunde sindssyge?

Sæt dig i din bil i frokostpausen med solbriller på, og peg med en hårtørrer på forbipasserende biler. Hold øje med, om de sænker farten.

Kald dig selv over samtaleanlægget uden at forvrænge stemmen.

Når nogen beder dig om at gøre noget, så spørg altid, om de ønsker pommes frites til.

Stil din skraldespand på skrivebordet, og mærk den “Indbakke”.

Hæld koffeinfri kaffe i kaffemaskinen i tre uger. Skift til espresso, når alle er kommet sig over koffeinafhængigheden.

Skriv “For seksuelle ydelser” på alle dine checks.

Spørg folk, hvilket køn de har. Grin hysterisk, når du hører svaret.

Sig “ud af huset”, når du køber mad i en drive-in-restaurant.

Råb: “Jeg vandt, jeg vandt”, når der kommer penge ud af pengeautomaten.

Råb: “Løb for livet, de er sluppet løs”, mens du løber mod parkeringspladsen, når du forlader Zoologisk Have.

Sig til dine børn over middagen: “Vi er desværre nødt til at afskedige en af jer på grund af økonomien.”