问题
I just encounter a problem similar to http://www.ruby-forum.com/topic/216433
I need to access controller instance variable from helper.
Here is the code I have done, and it's not work.
Controller:
class ApplicationController < ActionController::Base
helper_method :set_background_type #for action only background setting
#for controller-wise background setting
def set_background_type(string)
@background_type = string
end
end
Helper:
module ApplicationHelper
def background_type
@background_type || 'default'
end
end
Layout:
<body class="<%= background_type %>">
回答1:
After some searching. I got one solution from
http://api.rubyonrails.org/classes/ActionController/Helpers/ClassMethods.html
and the Controller becomes:
class ApplicationController < ActionController::Base
helper_method :set_background_type #for action only background setting
helper_attr :background_type
attr_accessor :background_type
#for controller-wise background setting
def set_background_type(string)
@background_type = string
end
def background_type
@background_type || 'default'
end
end
and remove the method from ApplicationHelper. It's work for this scenario, but I'm still curious,
is there a way to access controller instance variable for method in ApplicationHelper?
回答2:
If you're using erb templates, which I'm guessing you are, then you need to use erb syntax to call the helper method. Have you tried:
<body class="<%= background_type %>">
?
来源:https://stackoverflow.com/questions/5208689/rails-3-and-controller-instance-variables-inside-a-helper