Helper or partial?

I often find myself not being able to choose if I should use a partial
or a helper. They both get the job done but I want to know more about
why it’s better to use one or the other in certain situations etc.

What do you use, and when?

When I first saw helpers in the Todo list tutorial
Peak Obsession I thought this is
an
ugly solution

def display_items(ary)
result_string = “”
ary.each do |@item|
result_string << check_box(“item”, “done”, “onclick” => "
document.location.href=‘/todo/toggle_check/#{@item.id}’") + " "
result_string << @item.description + " "
result_string << link_to(“Edit”, :action => “edit”, :id =>
@item.idhttp://item.id)

  • " "
    result_string << link_to(“Destroy”,
    { :action => “destroy”, :id => @item.id http://item.id },
    :confirm => “Are you sure you want to delete this entry:
    #{@item.description
    }”)
    result_string << “

    end
    return result_string
    end

Having all the 'result_string = ’ and the ‘+" "’ is not very appealing.


In the very next section of the same Todo list tutorial
Peak Obsession the solutions
using
partials is much more appealing. It looks just like a template.

<%= check_box(“item”, “done”, “onclick” => "
document.location.href=‘/todo/toggle_check/#{@item.id}’") %>
<%= @item.description %>
<%= link_to(“Edit”, :action => “edit”, :id => @item.id http://item.id)
%>
<%= link_to(“Destroy”, { :action => “destroy”, :id =>
@item.idhttp://item.id},
:confirm => “Are you sure you want to delete this entry:
#{@item.description}”)
%>


I don’t think I would include things like check_box() or link_to() in a
helper. I would use a helper for something very small like the format
dollars helper in the Rails book p98.

module ApplicationHelper
def fmt_dollars(amt)
sprintf(“$%0.2f”,amt)
end
end

In this helper there is no appending to a string and no other helpers.
It
just does a tiny task. The simple call in the template <%=
fmt_dollars(%product.price) %> also indicates this is a method as
opposed to
a big chunk of partial template being inserted <%= render_partial
“display”,
@item %>.

  • Peter

My very straightforward rule of thumb is this; use partials, and if
they start to get horribly cluttered with lots of logic, change them
to helpers. I also sometimes mix the two, so use helpers to contain
logic and call out to partials to handle the actual rendering.

It’s all a style preference - I don’t like my templates/partials full
of code as they just get unreadable and horrible to maintain.

Dumb newbie question: Is it possible to output content from a helper
using something like ‘h’, or do you have to build up the string and
return it.

I’d been presuming you have to use a string because the helper might
not be view related.