DRYing rails view: partial vs helper [duplicate]

烈酒焚心 提交于 2019-11-30 11:14:34

I would say this is a great example of a partial.

I reserve helpers for generating arbitrary dynamic content. This is kind of a loose description so how about an example: I would make a helper that splits an array of ActiveRecord objects and displays them into N columns. In this case the passed object's structure is being leveraged in some way in order to generate the content, but the content itself is unimportant. If you think about it, form_for also fits this description.

Conversely partials are great for 'static' content, that needs to be reused on multiple pages. For instance you would create a partial to render a single item. The partial determines a particular items 'static' representation.

Your example fits much better into the second bin, in my opinion. Since the @item isn't being manipulated to generate the content, in fact it is hardly being used. It seems this helper is mostly glue code for other appropriately created helpers (share_button and marks_bar). The perfect use case for a partial!

I'd use a view partial for this. Good rule of thumb: if HTML is the output, use a partial. Helpers are not the junk drawer of your Rails app—they should really be used to output data, not presentation. Though I usually recommend people eschew helpers in general, in favor of presenters, which are vastly underutilized in the Rails world.

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