bricker
bricker

Reputation: 8941

Rails navigation

I am building a way to easily include navigation (tabs and subnavs) in my views. I should be able to have different navigations for different controllers, and for different actions within those controllers.

Currently I am using this simple helper method:

def nav_for(tabs_hash, *active_tabs)
  content_tag(:div, 
    tabs_hash[:tab_info].map { |tab| tab == 'spacer' ?
                            content_tag(:div, '', :class => 'nav-spacer') :
                            link_to(tab[:name], tab[:path], :class => [tab[:class], ("active" if active_tabs.include? tab[:id])].join) 
                  }.join("\n").html_safe,
  :class => tabs_hash[:div_class])
end

Which takes a hash that includes the info for the navigation items and parses it out. I am putting these hashes in methods in the controllers, but this prevents me from accessing the navigation hashes from other controllers.

My question is, where would be the best place to store the navigation information? It's also important that it has access to parameters, because some links are dynamically generated based on query strings.

I'm just looking for the best practices for this scenario. Thank you!

Upvotes: 0

Views: 289

Answers (3)

mliebelt
mliebelt

Reputation: 15525

I think the following could work for you:

  • Use your helper method with the one argument of a hash.
  • Define a class method in your super controller (e.g. def ApplicationController.tabs_hash(params) ....
  • In that method, define the default structure of your hash that could be used by all other controllers, but define it through a series of other class methods. def ApplicationController.tabs_hash(params);self.top_hash(params);self.middle_hash(params);self.bottom_hash(params);end
  • You are now able to define the concrete methods in your controller (as class methods). If you want you can mix and match methods from other controllers.
  • If not defined you will use the default behavior defined in ApplicationController

The pattern is that of an abstract method, and it works here because Ruby is using inheritance on the class side as well, so class methods may use super as well.

Upvotes: 0

eugen
eugen

Reputation: 9226

You should look into using the Simple Navigation gem. It does exactly what you are trying to do, and the configuration options are powerful.

Upvotes: 1

Devin M
Devin M

Reputation: 9752

I would say that use of formatting and markup in a helper is a bad idea, why not split this off into a layout partial which would abstract the data from your view. As far as storing the data I would consider how flexible this needs to be at runtime. Can you get away with using a YAML file to define links?

Upvotes: 0

Related Questions