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

前端 未结 1 539
悲&欢浪女
悲&欢浪女 2021-01-04 09:44

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

相关标签:
1条回答
  • 2021-01-04 10:19

    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.

    0 讨论(0)
提交回复
热议问题