Rails helper distance_of_time_in_words ported to C#

Posted by andy gaskell on Sep 29th, 2008

kabouter can scale.While learning rails I came across a very cool helper method called distance_of_time_in_words. You’ve probably seen this method in action if you’ve used Twitter – no guessing about time zones and as a user I think it’s a nice touch. So on to the port itself…

The Good
C# is automatically faster because everyone knows Ruby is slow and that rails can’t scale.
Seriously though, the port to C# uses resource files so internationalization is handled by simply adding a translated resource file to your project.

The Bad
C# doesn’t have the concept of static extension methods. To me DateTime.DistanceOfTimeInWords would be much nicer than DateHelper.DistanceOfTimeInWords.
Range support in the language is hokey at best. No ranges in switch statements. bleh.

The Ugly
The code! If you compare the C# version to the Ruby version it’s a little ahhhhhhhhhhh… inelegant? The Ruby version weighs in at 28 lines of readable code. The C# version is a b-e-a-s-t with 55 lines of code including 2 helper methods. I’m open to any suggestions in making the C# code shorter or more readable.

The Rest
The method time_ago_in_words has also been ported. Altogether the helper code is 74 lines – also included is over 250 lines of test code. All examples listed on the Rails page were also included in the test.

You can grab the code here or at the subversion repository http://svn.gaskell.org/helpers