问题
From my understanding, helpers are mainly used to clean up views from some view-specific logic.
But on my currently new project (legacy application), I've stumbled upon a lot of helpers that look like this
def itemprepare
render :partial => 'items/itemlist_summary'
end
Is this correct? Rendering a partial to me seems like something you would want to do in the view, as it doesn't include any logic that needs to be abstracted.
Should I just inline all of these helpers?
回答1:
Rendering a partial doesn't belong in a helper. Helpers should help you to do things that contain logic. Logic doesn't belong in the controller unless it's logic to render partials and decide if something should be displayed or not.
回答2:
Although you generally shouldn't use helper methods to render partials, I can see how in some situations that might be necessary. For those circumstances, you need to use the concat method:
def itemprepare
concat(render(:partial => 'items/itemlist_summary'))
end
回答3:
Like Ajedi32 says, partials use belongs to views but sometimes it's useful to use them in helpers. I hope it's useful to show what I've done in my application:
I've been following the excellent article Thinking of Rails Helper to help DRY our view. I'm using Jquery Mobile with a fixed header, nav-bar, navigation panel and a footer.
In every page I need to include the footer and the navigation panel, so usually it would have been:
<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /footer -->
<%= render "shared/nav_panel" %>
</div><!-- /page -->
at the end of each page.
Then I refactored the render partial into the application helper and now it is:
# app/helpers/application_helper.rb
def page_footer
footer = content_tag :div , :"data-role" => "footer" do
content_tag :h4, "Page Footer"
end
nav_panel = render(:partial => 'shared/nav_panel')
footer + nav_panel
end
and in the view I just call:
<%= page_footer %>
This is just a short example; in reality the app has a footer that changes according to the logged-in status, user language, etc..
回答4:
We have a couple of helpers like that in our project, but most of them are in our custom gem. Wrapping partial rendering with helper prevents application from knowing how the information is rendered and we can easily extend logic, change partial, or do whatever we want inside this helper as long as it renders requested part of the view. Sometimes these partial require some data that resides inside the gem itself and there is no need to expose it to application. So application calls helper method (sometimes without any parameters at all) that forms required parameters and locals and passes them to partial.
But when you're just rendering partial inside your application and you don't need any extensive logic around that rendering I don't think there's much use from creating new helper for every partial.
来源:https://stackoverflow.com/questions/8700759/using-rails-helpers-to-render-partials