Rails 3 and controller instance variables inside helper

I just run into a problem similar to http://www.ruby-forum.com/topic/216433

I need to access the controller instance variable from the helper.

Here is the code I made and it does 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 

Markup:

 <body class="<%= background_type %>"> 
+1
ruby-on-rails-3
source share
2 answers

After some searching. I got one solution from

http://api.rubyonrails.org/classes/ActionController/Helpers/ClassMethods.html

and the controller will be:

 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 this method from ApplicationHelper. It works for this scenario, but I'm still wondering

Is there a way to access the controller instance variable for a method in ApplicationHelper?

+3
source share

If you are using erb patterns that I assume you are using, you need to use erb syntax to call the helper method. You tried:

 <body class="<%= background_type %>"> 

?

0
source share

All Articles