The McDev Blog

Kevin McKelvin's perspective of the Ruby world.

Slim Templates

The Slim template engine seems to have gained a lot of popularity in the Rails community recently. Their site describes it as ‘A lightweight templating engine.’ For a long time I’ve loved Haml, taking the approach that I’d rather describe my intent than hard code HTML tags all over the place.

However, in hindsight having used Slim for a while it appears Haml might have stepped a bit too far away from HTML, including some cryptic syntax like ‘%’ signs to declare tags.  Slim takes a step back towards HTML.  It still uses the significant whitespace element of Haml and removes the annoying <>’s, but keeps you closer to the actual HTML that you’re describing.

Here’s an example of Slim (taken from a presentation I gave recently)

p = link_to "New Link", new_link_path
- @links.each do |link|
  div class="link"
    div class="title" = link_to link.title, link.url, :target => "_blank"
    div class="description" = link.description
    div class="manage"
      = link_to "Delete", link, :method => :delete, :confirm => 'Are you sure?'
= paginate @links

Nice and clean. The way it should be :)

To install it in your Rails app, just add it to your Gemfile:

gem 'slim-rails'

Then create a view using the .slim file extension to start using Slim.

Resources to check out:

For those using vim and the rails.vim plugin - the most recent version of the plugin supports .slim extensions for templates.

Out and About

I’ve spent the better part of the last 4 months looking into what the open source communities have been up to. The .NET stack was great to work with for 2.5 years, but I always find I get a thrill out of working with new things.

My books collection has been growing, particularly with PragProg titles. In the last 4 months I’ve read:

  • Seven Languages in Seven Weeks - Bruce Tate
  • HTML5 and CSS3 - Brian Hogan
  • Programming Ruby 1.9 (1.9.2 update) - Dave Thomas
  • The Rails 3 Way - Obie Fernandez

In the mean time I’ve come to love the Ruby programming language and the Rails framework - which has just recently released version 3.1.

I’ve been doing some learning projects over the last few weeks, including Platform45’s battleships developer challenge and I’ve been rewriting this blog using Rails 3.1.

jQuery PJAX @ Devs4Devs - 13 August 2011

Saturday 13 August was Devs4Devs at Microsoft’s Bryanston offices.  Apologies that I’ve taken so long to get my slides and code out, but they’re attached at the bottom of this post

Thanks everyone who attended my talk on using jQuery PJAX with ASP.NET MVC3.

Here are my slides and code from the talk.

Slides Code

Devs4Devs Jo’burg - 13 August

Calling all developers!  Microsoft’s Devs4Devs is happening on 13 August 2011 at their Bryanston offices.

Devs4Devs has to be my favourite developer event of the year.  There’s time to socialize with fellow geeks and learn how to use some really cool new technologies.

I will be presenting on using jQuery PJAX to speed up client side performance with the ASP.NET MVC framework.

A list of presentations and the registration link can be found on Microsoft’s South Africa Developer Platform blog, here

Dynamic Languages & DLR Presentation - Languages UG

Thanks for the great turn-out at the Microsoft Community Night on 12 July, we had a full room for the languages UG!

For those who weren’t there - I gave a talk on Dynamic Languages and the DLR on Tuesday 12 July.

Here are the resources from the talk:

IronPython: Clay: System.Dynamic:

And here’s the code used to call a Python script from C#, using the DLR interop and dynamic keyword:

var engine = IronPython.Hosting.Python.CreateEngine();
var scope = engine.Runtime.UseFile("");
dynamic greeterClass = scope.GetVariable("Greeter");
dynamic greeter = greeterClass();

dynamic s = greeter.sayHello("Kevin!");


Entity Framework 4.1 Hooks – DRYing It Up With EFHooks

One of the things I fell in love with about Rails is its automatic management of timestamps on data.  When you create a new entity, it sets the created_at field.  When you Update it, it sets the modified_at timestamp.

For a long time I’ve used NHibernate as my ORM of choice for .NET and registered listeners for the pre-insert and pre-update events in NHibernate to handle this for me.  Now that Entity Framework 4.1 is out and becoming more useful I was interested in seeing how similar things could be done.

Entity Framework’s extension points are very limited compared to what NHibernate is capable of, but there is enough there to get you through most borderline scenarios you’ll hit while working with Entity Framework.

The problem I have with using the extension points is that you have to embed code inside your DbContext class to hook into the inserts, updates and deletes.  This means you’re mixing concerns of hooking into the extension point and the logic of what the hook must actually do.  This means it becomes difficult to test your hooks in isolation and that your DbContext class can become exceptionally long.

In comes EFHooks.  It’s a project I’ve just started to make it easier to hook into Entity Framework.  Check the code out on Github here.

EFHooks allows you to separate the concerns of writing pre-action hook code from accessing the extension points and registering your hooked code for execution.  This means unit testing your hook without using a DbContext becomes easy.

Here’s an example of a hook to run before any entity that inherits from ITimeStamped gets inserted.  Everything is strongly typed, so only ITimeStamped entities will be passed into this hook.

public class TimestampPreInsertHook : PreInsertHook<ITimeStamped>
    public override void Hook(ITimeStamped entity, HookEntityMetadata metadata)
        entity.CreatedAt = DateTime.Now;

This means you don’t need to write code to set your CreatedAt date every time you create an entity that implements ITimeStamped.  By the same pattern you could use .NET reflection on System.Object and not even have to use an interface.

Note I said “pre-action” – This handles 99% of the use cases I’ve ever hit.  I’m working on a way to handle post-action hooks as well and I’ll have it all in a Nuget package as soon as it’s stable.

Check the code out, build it, play with it and please let me know if you have any problems with it.

(Update: Post-actions are also implemented and the package is available on NuGet here)


EFHooks on Github

Android vs WP7

A couple of months ago I blogged about my experiences with WP7 on the HTC Trophy.

Well soon after that I sat playing with Android 2.3.3 and began seeing holes in WP7 that I didn’t even know were there before.

The first point is location based, Google has got far more market penetration here in South Africa than bing has. In preparation for the Soccer world cup last year, Google beefed up their maps of South Africa including Street View, local business references, their geolocation quality and their routing engines. If I type something like “Roman’s Pizza” into my droid device it shows me the nearest Roman’s Pizza restaurants. If I type that into bing, it asks if I meant Romania.

If I were sitting in the USA this wouldn’t be an issue since bing’s market penetration seems to be far better there.

The next thing I noticed was the smoothness of apps. WP7 still has a few bugs to kill in its threading implementation which will hopefully be resolved by WP7.1. The result is that WP7 apps tend to jitter as you’re scrolling through them while visual states are updating, or when items are being added or removed from a list. The Facebook and Twitter apps demonstrate this clearly.

On Android I fire up TweetDeck and it’s silky smooth from the moment I open it. No jittering, no lagging.

That brings me to my next point, community apps. WP7 is still young and I was willing to hold on a bit for the community to catch up with apps, but it’s been slower than anyone expected to the point that it’s actually painful. At this point there is still no decent instant messenger for WP7. Whatsapp is nowhere to be seen, nor is Skype or Google Talk. (Yes… I know that Skype is on its way with WP7.1, but at the moment we’ve got nothing).

There’s just a much broader support for Android than WP7. A few other examples that have no close matching app on WP7 are the Formula 1 live timing app which I now use for every F1 race, TweetDeck, Winamp, SoundHound, Guitar tuner and Harvest time tracker.

I’ve also found that similar apps have better functionality on Droid – e.g. YouVersion Bible can stream an audio version of a passage in Droid which can’t be done in the WP7 version. I mentioned TweetDeck before, I know Birdsong is decent on WP7, but Tweetdeck is free and does an equally good job as the paid app on WP7.

When the WP7.1 update hits, I believe the two operating systems will be pretty much on par with each other – with WP7 in the lead for enterprise integration with Exchange and Lync Server.

WP7 has a great edge in a few areas already. I definitely prefer the IE based web browser in WP7 over any of the browsers on Droid. 3D graphics in games are absolutely stunning on WP7 with its Direct X based hardware accelerated rendering. Also the simple ability to fire up the camera from the lock screen is very useful.

App development for WP7 is also light years ahead of Android’s. While the tools for Android are very good (Eclipse + Java + ADK with Android Emulator), the tools for WP7 have the edge with the Blend + Visual Studio + Silverlight combination.

As things stand right now, WP7 really is a great phone OS, but its community is lacking and bing really sucks in South Africa. When the Mango update hits, when Whatsapp finally releases a client for the WP7 platform and when bing’s search in South Africa improves (or we can change over to Google search in WP7) I will probably change back over to using Windows Phone.

Getting Started With TypeMock Isolator (in VS2010)

I started playing with TypeMock Isolator this morning as an alternative to using the Moles framework from Microsoft Research.

Isolation frameworks allow you to intercept and redirect calls made to concrete call sites and replace them with a delegate. If that sounds like a bit of gibberish consider this scenario:

If you have a class that makes a call to DateTime.Now to check against an expiry date and you want to test that it expires on a future date, you need to control what the static DateTime.Now returns. That’s where an isolator comes in.

To get started with TypeMock, once you have it downloaded and installed you just need to add references to the DLLs from your GAC. TypeMock’s website still shows VS2008 instructions which are slightly different from VS2010.

To get going with NUnit and TypeMock, first create a class library:


Add a reference to NUnit from NuGet


When working with C#, add references to TypeMock and Typemock.ArrangeActAssert to your unit test project.


And you’re ready to start writing isolated tests!

To run a test with TypeMock Isolator is pretty simple, just add an Isolated attribute to your unit test and use TypeMock’s fluent Isolate API to mock the method calls.

Returning to our DateTime example, here’s how you could Isolate a static call to DateTime.Now:

[Test, Isolated]
public void ReplaceDateTimeNowWithValue()
    Isolate.WhenCalled(() => DateTime.Now).WillReturn(new DateTime(2010, 1, 2));

    Assert.AreEqual(new DateTime(2010, 1, 2), DateTime.Now);

Mocking out a concrete instance method is also easy. Below, I’m mocking the behaviour of a method in a sealed class - UserRepository.GetQuery()

[Test, Isolated]
public void LoginWithRealRepository()
    // arrange
    var ur = Isolate.Fake.Instance<UserRepository>();
    Isolate.WhenCalled(() => ur.GetQuery()).WillReturn(new List<User>
                                                        new User
                                                                Username = "kevin",
                                                                Password = "abc"

    var login = new UserLoginController(ur);
    User loggedInUser = login.Login("kevin", "abc");

    // assert

There’s a great debate about when isolation frameworks should and shouldn’t be used. Having learnt how to do unit testing via TDD without requiring an isolator I would still use it sparingly, only pulling it in when I want to test the class whose responsibility is to bridge the divide between my code and a global state such as a database or the file system. A tool like this isn’t an excuse to write code with mixed concerns simply because it can be isolated later. Writing testable code helps drive good object oriented design and loose coupling – both are important design objectives.

TypeMock Isolator is an impressive bit of software. There are clear advantages in using this in the future.

It allows developers to be more pragmatic about when to write polymorphic code and focus more on testing behaviour rather than how to fake things in tests. Truth be told it makes unit testing C# feel a lot more like testing in dynamic languages.


TypeMock Home Page

TypeMock Isolator

@Typemock on Twitter

Unit Testing & Mocking Presentation (ERDDUG June 2011)

On Saturday I gave a presentation at ERDDUG on Unit Testing, Mocking and basics of TDD.

Slides are on Slideshare:

Unit testing

Also here’s the sound recording of the presentation.

Thanks to Misko Hevery for the diagrams I used in those slides to illustrate class dependencies. If you’re interested in some more detailed stuff, he has an excellent talk in the Google Tech Talks on designing for testability. It’s available on YouTube here

ERDDUG May Meeting

Thanks to Darrel Schreyer (@dwschreyer) for today’s presentation at the East Rand Developer & DBA Usergroup.

This month Darrel covered an introduction to the WCF framework, particularly around Bindings and Contracts and using a shared Model class between multiple assemblies and multiple targets.  It was a great introduction for those of us who hadn’t been using much of WCF before.

Next month I’ll be presenting on TDD, Unit Testing and Mocking at the ERDDUG June meeting.  More details to follow.