Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...