How does rails pass objects to the view?
If an action looks like:
def show
@post = Post.find(params[:id])
end
I can then do:
<%= @post.title %>
How does it pass the object to the view?
Since my action has only one line, what programming technique or pattern is used to take the @post
object and pass it to the view (template) page?
I know it assumes the view will be the sa开发者_JAVA百科me name as the action, but how does it do this?
for example like this: we will transfer MyController variables to MyView variables
class MyController
def my_action
@my_variable = 100
end
end
class MyView
def process_view_with_variables(variables)
puts variables.inspect # => [{"@my_variable"=>100}]
variables.each do |var|
var.each {|name,value| self.instance_variable_set(name,value)}
end
puts self.instance_variables # => @my_variable
# .. view_rendering here
end
end
# create new view and controller instances
my_controller = MyController.new
my_view = MyView.new
# call my_action method in MyController instance (which will initialized some variables)
my_controller.my_action
# let know about instance variables in our controller
puts my_controller.instance_variables.inspect # => ["@my_variable"]
# simple array, for store variables (this is like a proxy)
controller_variables = []
# transfer instance variables from controller to proxe
my_controller.instance_variables.each do |variable|
controller_variables << {variable => my_controller.instance_variable_get(variable)}
end
# let know which instance variables bow in proxy array
puts controller_variables.inspect # => [{"@my_variable"=>100}]
# call method process_view_with_variables which will transfer variables from proxy to view
my_view.process_view_with_variables(controller_variables) # => [{"@my_variable"=>100}]#
First you need to look at the binding class. The book "Metaprogramming Ruby" (highly recommended BTW) sums them up nicely: "A Binding is a whole scope packaged as an object. The idea is that you can create a Binding to capture the local scope and carry it around."
Then a look at the ERB class should answer your question. This example is straight from the docs:
require 'erb'
x = 42
template = ERB.new <<-EOF
The value of x is: <%= x %>
EOF
puts template.result(binding)
I hope that helps.
精彩评论