Topic: Uncluttering Application Controller

I have a partial /app/views/shared/_menu.rhtml that looks like this:

<% @menu_items.each do |menu_item| %>
    <p><%= link_to menu_item.link_text, { :controller => menu_item.controller, :action => menu_item.action } %></p>
<% end %>

My application controller has a before_filter to dynamically create the array of menu items based on whether the user is logged in, etc.... I'd like to clean it up by making a separate menu controller.

I can think of 2 ways to do this but I'm not sure how to do either of them or which is best. One way would be to call the menu controller directly from _menu.rhtml. The other would be to make the application controller delegate the creation of the menu array to the menu controller. In the latter case, the application controller would still have to store the array, so maybe the first solution would be cleaner.

Re: Uncluttering Application Controller

Are you sure you want to make a new controller?  Controllers are responsible for certain urls, it sounds like you just need a new place to put your code.

I'd recommend adding the code to application_helper.rb in /app/helpers/.  Any code you put in there will be automatically available to all views.  And if you put the line:
include ApplicationHelper
in your application controller then you can use those methods in all the controllers as well.

Re: Uncluttering Application Controller

Good point. I'm still getting used to the structure of a Rails app. But if I put it in application_helper.rb then that file ends up being cluttered with menu stuff, which is just as bad as cluttering application.rb. I have a function to create each menu item (or return nil), so it ends up being a lot of clutter.

Now that I'm thinking about this fresh for today, I'm thinking what I really need is a Tableless model that will create and return the array of menu items. I'll still call it from the application controller. I think I'll give that a try.

BTW, I realized last night that there's a better way than the code I put in my original post. Now I'm using url_for to create each menu item so now my menu partial looks like this:

<% @menu_items.each do |menu_item| %>
    <p><%= link_to(menu_item.link_text, menu_item.link_url) %></p>
<% end %>

Re: Uncluttering Application Controller

I wrestled with it for a while and finally hooked up a model to store the array of menu items, only to learn (the hard way) that url_for is only available in views and controllers. I thought about hacking around that but ultimately thought better of it. Then I realized I can just make a MenuHelper and call it from the ApplicationController, which pretty much does what I wanted in the first place- provides one place for menu code without cluttering anything else. Thanks for pointing me in that direction, Danger.

Re: Uncluttering Application Controller

Awesome.