StackNG
StackNG

Reputation: 591

Rails 3 and Controller Instance Variables Inside a Helper

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 %>">

Upvotes: 1

Views: 3253

Answers (2)

StackNG
StackNG

Reputation: 591

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?

Upvotes: 3

Josh Deeden
Josh Deeden

Reputation: 1690

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 %>">

?

Upvotes: 0

Related Questions