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?
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.
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.
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.
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
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