Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing only two variables between controller and view - best practice?

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 Quality Checklist)

What is the suggested way for example - to pass two arrays and their total values calculated in the controller, which makes 4 instance variables? Or to pass to a Javascript data table the: data, total items, total items displayed?

like image 578
mbdev Avatar asked Aug 13 '11 14:08

mbdev


1 Answers

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:

  1. data array
  2. total data items
  3. total items displayed

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.

like image 61
M. Cypher Avatar answered Oct 18 '22 12:10

M. Cypher