Navigation helper acting weird
The I’ve handled tabs in the past has always bothered me. I’m trying to handle them a different way, now that I have better options. Just like anything you do the first time, I’m sure this could be improved upon—but here’s what I have:
1 2 3 4 5 6 7 8 9 10 11 | # application_helper.rb def main_navigation(links) li_class, link_class = 'left', 'non-current' nav_bar = Array.new links.each do |link| li_class = 'right' if controller.controller_name.downcase == 'settings' link_class = 'current' if controller.controller_name.downcase == link.downcase nav_bar << "<li class='#{li_class}'>#{link_to link.capitalize, '/' + link.downcase, :class => link_class}</li>" end nav_bar end |
I’m calling this helper like this:
1 2 | # layout <%= main_navigation ['dashboard','messages','settings'] %> |
Yes, each link does correspond to a controller, and the reason I’m changing the ‘settings’ tab is because I want it off to the right, separated from the other tabs. The concept is obvious, but this thing is acting crazy. Here’s what happens when I click…
- Dashboard—All three list items have
class='left'and each tab hasclass='current' - Messages—All three list items have
class='left'but this time, the Dashboard tab hasclass='non-current' - Settings—All three list items have
class='right', and only the Settings tab hasclass='current'(which actually is the current section, making it the only one to follow the ‘current’ rule)
It seems like the li_class always applies to all three tabs, but the link_class doesn’t. Is there something blatantly wrong with this?
UPDATE—the only trouble I’m having is with the ‘left’ and ‘right’ settings. All tabs are left if I click on Dashboard or Messages, and all tabs are right if I click on Settings. I had the li_class and link_class being initialized outside the loop, like an ignoramus. But I can’t seem to get the settings tab to be the only tab with class='right'.

Nick Tuesday, 13 Mar, 2007 Posted at 08:44AM
I like your approach to the navigation menu. I always just put the menu inside of the layout template. In the past, I’ve created a partial to include the menu, but this is much cleaner. I think my PHP background is causing my Rails development to use sloppy techniques.
Chris Tuesday, 13 Mar, 2007 Posted at 09:20AM
Shouldn’t your tests be for the
linkvariable, and notcontroller.controller_name?That is:
Ryan Tuesday, 13 Mar, 2007 Posted at 09:34AM
Yes. Like I said… ignoramus. Thanks.
Total redemption for me beating you to the answers on Nick’s site!
Chris Tuesday, 13 Mar, 2007 Posted at 09:36AM
Sometimes looking at a function for too long makes the obvious completely disappear :-p
Ryan Tuesday, 13 Mar, 2007 Posted at 10:45AM
Definitely. It’s hard to give it up, too, so I end up going in circles until I eventually ask someone (or post about it—that sometimes helps, too).