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

Bulletproof Ajax with ASP.NET MVC (this time with jQuery)

Posted by andy gaskell on Aug 10th, 2008

As a follow up a recent post about using unobtrusive javascript and Ajax in your ASP.NET MVC applications, I ported the Bulletproof Ajax bookstore application to use jQuery instead of Hijax. This led to more terse code - lines of javascript were reduced from 178 to 41. If you’ve spent at least few hours jQuery then you should find that the new code is also more readable. No server side code changes were necessary.

jQuery is also really easy to extend - I wrote a couple of extensions that would be usable throughout an application. Here’s the extension I wrote to produce the ubiquitous yellow fade effect:

(function($) {
   $.fn.yellowFade = function() {
    return this.css({backgroundColor: "#ffffcc"})
    .animate({backgroundColor: "#ffffff"}, 1500, "linear");
   }
 })(jQuery);

Calling this method flows with the rest of jQuery style chaining of methods:

function(data) { $("div#basket").html(data).yellowFade(); });

This one liner is a callback from our http post to the /Cart/AddProduct. The data parameter contains the response from the server. $("div#basket") is getting the container div from our shopping cart. Then we replace the html within the shopping cart div with the response from the server and follow it up with a yellow fade to provide user feedback.

Code is downloadable here. The demo.