Should Rails helpers assume an instance variable exists or should they receive them as parameters?

こ雲淡風輕ζ 提交于 2019-11-28 18:34:54

Receive them as a param. Otherwise, as the app grows, it gets very difficult to trace where the instance vars are being set when refactoring, troubleshooting, etc.

Also, I believe there's a general best practice to only use instance vars in views within the initial template...and from there you should pass the var into helpers and other partials.

I'd say you should always pass the variables explicitly to your helper for 2 reasons:

  • you control exactly what you do

  • above all, you can test your helper

I don't know if there is any named principle governing this sort of thing but I would pass an argument. Not only will the argument make your helper easier to test and your application's data flow easier to follow but it will also let you use one helper for a single instance as well as a list; if you pass an argument then both:

<%= cockadoodledoo @egg %>

and:

<% @eggs.each do |egg| %>
    <%= cockadoodledoo egg %>
<% end %>

will work as expected without introducing a special cockadoodledoo that handles a list in @eggs rather than a single @egg.

Since helper messages are mixed in to all controllers, hence available to all views (including partials and layouts), it's always wise to establish a clear contract - the parameters.

The only exception I could think of is when a instance variable is also available to all views and controllers, like a menu or something similar.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!