Coding Guidelines: Instance variables in views

Jirka Tomasek jtomasek at redhat.com
Fri Aug 17 08:52:46 UTC 2012


On 08/16/2012 05:05 PM, Matt Wagner wrote:
> Hi folks,
>
> I've noticed that we've been objecting to patches using instance
> variables to pass information to views, so I went to see our coding
> guidelines page[1] to read about why.
>
> It makes very clear that it's bad, but it doesn't really explain the
> right way. I'd hoped that the Coding Guidelines page would be more of a
> guide on how to do things the right way.
>
> I've really only found one blog post[2] that addresses the issue, and it
> doesn't really give a great example. It still uses an instance variable
> in the controller, but inside of a view it passes it as a local
> variable. It's more specific, sure, but it's not abundantly clear how
> that actually makes anything better, or why an instance variable from
> the controller to the view is okay but a view to a partial is not okay.
>
> Can someone with a more concrete understanding of the right way update
> the wiki page, or send me some pointers so I can do so? I'd love for the
> page to show the right way, maybe an example of rewriting the "bad way"
> into the right way, rather than just giving a stern warning that it's
> bad.
>
> -- Matt
>
> [1]
> https://www.aeolusproject.org/redmine/projects/aeolus/wiki/Coding_Guidelines
>
> [2]
> http://rails-bestpractices.com/posts/27-replace-instance-variable-with-local-variable

I don't like the sentence "Don't use it for passing variables to view. 
Never." which is actually one of the first things that any Rails book 
teaches you. I agree that we should try to reduce using instance 
variables in controllers where possible to avoid cluttering controllers 
with them.

The blog post you sent points out the reusability of partials so passing 
the variables as locals helps avoid requiring use of eg. @post in all 
partials instances. Imho it depends on the desired use of the partial.

We have discussed with Imre the alternative way to pass variables from 
controller's action to view. It can be done similar way as with partials:

   ...someactioncode...
   render :action => :index, :locals => {:post => post}
end


but I have never seen this used anywhere in controller and I assume this 
is not the "Rails way".

Jirka



More information about the aeolus-devel mailing list