views:

132

answers:

1

Hi!

I have a little bit of trouble creating a menu in Rails. In ApplicationController I have a set_menu method:

def self.set_menu(menu, options = {})
  # ...
end

This is called from each controller like this:

class UsersController < ApplicationController
  set_menu :users

  # ...
end

In set_menu, I need to create a variable that I later can reach in a helper method to find out which of the menu items that is the active one. I got this working by using a class variable. This worked fine in development, but it turns out that Rails caches this variable in production, so the active menu never changed.

So, how do I in set_menu create a variable that I can reach from a helper method and that production stage does not cache?

+1  A: 

Instance variables are shared between the controller and the view, including helpers.

class ApplicationController

  def self.set_menu(menu, options = {})
    before_filter(options) do |controller|
      controller.send(:set_menu, menu)
    end
  end

  # ...


  protected

    def set_menu(menu)
      @menu = menu
    end

end

# in your view
<%= @menu %>

If you want to create more complex navigation menu, have a look at my Tabs On Rails Gem.

Simone Carletti
Thank you! That was a really good solution for this problem.
rejeep