How are Rails instance variables passed to views?
Ruby on-RailsRuby on-Rails Problem Overview
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?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
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
Solution 2 - Ruby on-Rails
The decent_exposure gem is an alternative to Rails' standard controller instance variable behavior. The readme has a good writeup about the issue.