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
Instance variables will be stored on the heap. and the object on heap ).
Instance variables in view filesA variable set in Rails controller starting with @ sign are called instance variables. The specialty of instance variables is that they're available in our Rails views. We don't need to pass them explicitly to our Rails views. That's why in the index.
Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables can be declared at the class level before or after use. Access modifiers can be given for instance variables.
A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words . This method is helpful whenever you want to display time in this specific format.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With