Found this Best Practice and it\'s even got inspection in RubyMine: \"Only one or two instance variables are shared between each controller and view.)\" (Ruby on Rails Code
I think the most sensible way to respect this is to go from many simple objects to few complex objects.
Let's say, for instance, you have three separate variables now:
Now, instead of using 3 separate instance variables (one Array
, two Fixnum
), you could create a Hash
which holds all three of them, or perhaps define a new class which responds to methods such as total_items
that you can call in the view.
In fact, as one example, will_paginate
does something like this: A paginated collection of items is not simply represented as an array, but as a WillPaginate::Collection
object, which responds to methods such as current_page
, total_pages
, total_entries
, etc. This is more natural than having separate variables, since it more accurately maps the relationship between the information you're interested in sharing with your view.
As a rule of thumb, I would suggest that anything which corresponds to closely related information should always be in one instance variable, but anything that isn't really related at all should not be "forced" into one variable because of these best practices. Every rule has an exception, so if, for example, you really have 5 different components in your view which have absolutely nothing to do with each other (which is rare), blindly following the best practice might not be the best idea.
Bottom line: Understand the idea behind these rules, and you'll know what to do.