What Ruby technique does Rails use to make my controller methods render views?

走远了吗. 提交于 2019-12-03 11:38:16

On the controller, there is a method called render_for_text. This takes a string and sets the result as the response body. Even if you don't render as text, rendering a view file simply reads the file's contents, evaluates it, and passes it to the render_for_text method. The method then stores sets an instance variable called @performed_render to true, which tells rails that the controller has already rendered a view.

There is then a method called performed? that indicates whether or not the render action has been called. It does this by checking if @performed_render or @performed_redirect is true.

With the above information, the very first line of the render method should make sense now, and hopefully answer your question:

raise DoubleRenderError, "Can only render or redirect once per action" if performed?

When rendering a view, Rails initializes an instance of the appropriate view template with copies of the instance variables in the controller. So the instance variables aren't actually inherited by the view, but rather copied from the controller into the view before the view is rendered.

I haven't looked up the exact details in the source, but the above explanation should at least outline the general idea of how it works.

Jamis Buck wrote quite a bit about implicit routes a few years ago here.

I believe the code you're looking for is in Resources. Rails looks at the inbound request and (for RESTful routes) goes here to determine the controller and action if they aren't specified.

Update: Controllers are a really complex part of the Rails framework. It isn't quite as simple as a single Ruby class with a single method (which is why super isn't really needed, but a series of calls both before and after your individual method is called.

Rack handles the request and passes it to Rails which does the routing, delegates to the instance of ActionController for the action (which may or may not have been coded by you), then passes the result of that to the rendering process.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!