Rails tabbed navigation helper

20 May 2009 - Mississauga, Ontario

The Opportunity:

You have just built a fantastic website for a client using Rails (of course). Everything is to spec, your tests are all passing, your delivering early and are waiting for your cheque to be cut. Then, all of sudden, your client rushes into the room and says,

Hey… so can you like make it so that whatever section of the site I am on gets highlighted in a different color on the navigation? You know, just give them some feedback. That’s really easy right… shouldn’t take more than a few minutes?

Any good web developer will tell you that at least one of the things the client said is right, it shouldn’t take more than a few minutes to add navigation feedback, however if my code reviews, water cooler conversations and open source browsing has taught me anything its that this problem is not always easy to solve.

Actually, let me rephrase that… there is no design pattern for solving it. There is not a set way of doing this. It’s not hard by any means, but each developer has their own way of doing it. Some people like using regular expressions, others like to use… shutter… global variables. Then some people even create entire plugins and libraries to help them do this tabbed navigation.

The guys over at The Rails Way did a great post about Tab Nav helpers where they outlined some of their favorite methods. To be honest, I didn’t like any of the ones they put out. I looked through the comments and found one that resonated with me. It was Andrew Hobson’s layout_link_to helper method:

Liquid error: No such file or directory – pygmentize -l ruby -f html -O encoding=utf-8

There are lots of things I like about this solution but a few places where I thought it could be improve. Firstly, I want to be able to pass some more options to the link in case I have a custom CSS class or if I want to pass the :target attribute. Also, this helper only works when you are on the exact path specified. This works well, but what if you have a Projects Controller and you want the tabbed nav called projects to be highlighted when on the new, show and edit pages. It’s a pain right now since it only checks for equality of path, all you have to do is add a little string.include? instead of string ==. Here is my re-write that incorporates both of these fixes.

The Solution:

Liquid error: No such file or directory – pygmentize -l ruby -f html -O encoding=utf-8

So, there you have it… a simple and powerful tab nav solution for your next Rails application. Thanks to the Rails Way, Andrew Hobosn and yours truly.

Thank you so much,

Take care,

Kent