Where are instance variables in a Rails helper module stored?
railstutorial.org, ruby-on-rails
Solution
This answer tells in general about how instance variables are passed between controller and view: How are Rails instance variables passed to views?
So basically, if @current_user is set by a controller, that instance variable (along with all others) will be passed from your controller context on to the view context. If it has not been set by a controller, it will be set the first time a view uses it.
For more information, see the other answer. It is a good read.
Pasted from @mechanicalfish answer:
def view_assigns
hash = {}
variables = instance_variables
variables -= protected_instance_variables
variables -= DEFAULT_PROTECTED_INSTANCE_VARIABLES
variables.each { |name| hash[name[1..-1]] = instance_variable_get(name) }
hash
end
Passing them to the view (github):
def view_context
view_context_class.new(view_renderer, view_assigns, self)
end
Setting them in the view (github):
def assign(new_assigns) # :nodoc:
@_assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) }
end
Problem
A tutorial I am following has in the subdirectory `app/helpers` the below SessionsHelper module which is used by many controllers and views. But where is the instance variable `current_user` stored when it is first created? What is the class of the object where it is stored? When a controller first invokes the `current_user` method the `current_user` instance variable is created. When a view then invokes the `current_user` method how is it that a `current_user` instance variable is already present? Is `self` set to the controller object during the rendering of the view? ``` module SessionsHelper ... def current_user @current_user ||= User.find_by_remember_token(cookies[:remember_token]) end ... end ```