Saving the planet, one website at a time

Hi, I'm th3james. I build stuff with Coffeescript, Clientside MVC and Rails

Styling Active Links in Rails

We often want to style active links in our Rails to improve the users perception of their location in a given website. However, a:active is rarely sufficient when you’ve got sub menus on your site.

I went searching for people who’d already tackled this problem and found the post by ‘jammanbo’ on this page:

http://www.ruby-forum.com/topic/178087

jammanbo’s helper detects if the current path matches another path’s controller and action, returning ‘active’ or ” to use as the link class. While this is useful, there are many times when we want to match to a different level of specificity for links. For example, top level menus in sites I’m working on tend to match a controller, and sub menu entries to the action. Other times, we also want to match the route’s parameters.

Taking this into consideration, I came up with this helper:

This helper returns a string, either ‘active’ or ” depending on if the URI parameter matches. The optional second parameter defines the specificity, either

  • :action (default) match both controller and action
  • :controller match just controller, or
  • :complete matches all parameters in the route (except extra ?param=whatever)

To use it, simply drop it into your ApplicationHelper, then start styling links with:

Have fun!