Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Rails instance variables passed to views?

In my Rails app, I have a controller like this:

class MyController < ApplicationController   def show     @blog_post = BlogPost.find params[:id]   end end 

In my view I can simply do this:

<%= @blog_post.title %> 

I'm uncomfortable with magic. How is this achieved?

like image 328
superluminary Avatar asked Sep 17 '13 16:09

superluminary


People also ask

Are instance variables set within a controller method accessible within a view?

Are instance variables set within a controller method accessible within a view? Yes, any instance variables that are set in an action method on a controller can be accessed and displayed in a view.

What is an instance variable in Rails?

In Rails, instance variables (like @books ), are used to share data between your controller & views. But you can still use them normally, for your own classes.

Why we use instance variable in Rails?

Instance variables are in the instance class scope. In Ruby on Rails, because the way how that API was built, instance variables are also available in the views. You need to be aware of that new and create methods are commonly used in different ProductsController instances.


Video Answer


1 Answers

When the view is being rendered, instance variables and their values are picked up from the controller and passed to the view initializer which sets them to the view instance. This is done using these ruby methods:

instance_variables - gets names of instance variables (documentation) instance_variable_get(variable_name) - gets value of an instance variable (documentation) instance_variable_set(variable_name, variable_value) - sets value of an instance variable (documentation)

Here is the Rails code:

Collecting controller instance variables (github):

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 
like image 195
mechanicalfish Avatar answered Sep 18 '22 12:09

mechanicalfish