Building flexible menu in rails

I am not using this technique anymore! If you're looking to build menus in rails, I suggest you read about my new technique. I am keeping this post public for academic reasons

If you've ever developed a dynamic website, chances are that you had to implement a dynamic menu or a breadcrumb. You know, something like this (taken from Ecrire's admin bar):

Here's how I did it, without gems.

Basic needs

When I browse for a gem to do that, I wasn't too sure about what I wanted. Many gems tried to be too smart about what they do. What if you want a dumb menu renderer, something you can feed it menu items and it renders them for you. Something that needs to:

Admin::MenuHelper::Menu

Line #5-6: You need to include the ActionView helpers to have access to the methods within a view i.e.content_tag, link_to, etc.

Line #11-12: Raise an exception if no block is given. I did this because I wanted to make sure some items would exist from the get go. The block is then called and a reference to this menu is passed so it's possible to use menu.add.

Line #15: Where your add items to your menu. This method has a klass argument that is optional should I want to customize an item with a different class. A block must be given. More on this later.

Line #23: Renders the menu to the screen. What it does is that it passes the request object to each item so they can check if they have to be highlighted and then iterates every items and render them.

Admin::MenuHelper::Item

Line #29-30: Same as above, included to gain access to the view's helper methods.

Line #42: It's the block that will be called to check if the item should be highlighted or not.

Line #47: The render block that will generate the HTML output for this item. The item will have a class named active if the block needs to be highlighted.

The finale

Once you have all of your items configured, you can render it using menu#render