views:

58

answers:

2

Why does rails use @poop object instance variables instead of just a local poop variable in the generated code? Is there some foreseen common situation where it's useful rather than simply using a local variable here? I would think it makes sense to use a local variable and not attach something to the object namespace unless you need it there.

  # GET /poop/1
  # GET /poop/1.xml
  def show
    @poop = Poop.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @poop }
    end
  end
+2  A: 

It is idiomatic to use controller instance variables when you need to make those values available in the associated views and helpers. Otherwise the use of locally scoped variables in controller logic is probably preferable.

That said, if you find that your controllers are using a lot of variables (indicative of complexity) then best-practice would suggest that you move that logic into the models, keeping the controllers lean.

bjg
+4  A: 

Is there some foreseen common situation where it's useful rather than simply using a local variable here?

Of course there is. The default situation is like that. Check the source code of auto-generated (with use of script/generate/scaffold) view in app/views/poops/show.html.erb:

<p>
  <b>Field:</b>
  <%=h @poop.field %>
</p>
<%= link_to 'Edit', edit_poop_path(@poop) %>

If the variable was local to the controller method, how would the renderer access the element you found with find(params[:id])? respond_to doesn't directly call the component that renders the page. Instead, it delays its execution up to the point when local variables would already be out of scope. Then the only way renderer could communicate to what was calculated in the controller is with use of instance variables.

Pavel Shved