Featured post
What Ruby technique does Rails use to make my controller methods render views? -
just curious if knows ruby technique used accomplish following in rails framework.
if don't write, say, index
method on rails controller, rails still render index view file if url matches route. makes sense, because controller inherits parent class, must have own index
method.
however, if do define index
method, , tell set instance variable, still renders appropriate view. example:
def index @weasels = weasel.all # if omit line, rails renders index anyway. # if behavior defined in parent class's index method, # seems overriding method, index wouldn't it. # i'm not explicitly calling super method # actioncontroller::base, maybe rails doing that? render :index end
in pure ruby, expect have call super
behavior.
i assume rails uses kind of metaprogramming technique guarantee controller methods call super
. if so, can explain it? can point source code this?
update
as mladen jablanović has pointed out, initial mental model wrong; controller method doesn't render view; instead, both controller method and view rendering called framework code. apparent because can make controller method name - example, search
- , search
view rendered. i'm not overriding parent method in case, , framework code parsing controller method name , looking matching view.
still, framework must able detect whether or not controller method has called render
. that's small mystery me.
on controller, there method called render_for_text
. takes string , sets result response body. if don't render text, rendering view file reads file's contents, evaluates it, , passes render_for_text
method. method stores sets instance variable called @performed_render
true
, tells rails controller has rendered view.
there method called performed?
indicates whether or not render action has been called. checking if @performed_render
or @performed_redirect
true.
with above information, very first line of render method should make sense now, , answer question:
raise doublerendererror, "can render or redirect once per action" if performed?
- Get link
- X
- Other Apps
Comments
Post a Comment