Share variable between controller and helper in Rails
I have a little bit of trouble creating a menu in Rails. In ApplicationController I have a set_menu method:
def self.s开发者_运维技巧et_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?
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.
精彩评论