Forum: Ruby on Rails Helper versus Partial

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Fccf42643feb2aaf9e6b4bfce0d737cc?d=identicon&s=25 weepy (Guest)
on 2007-01-20 17:42
(Received via mailing list)
hi all,

Im looking for some pointers on best practices of when to use a helper
and when to use a partial.
A2c85dc5ee81b12e3cc0a6522e8d079d?d=identicon&s=25 Chris Hall (au5lander)
on 2007-01-20 18:35
(Received via mailing list)
first, helpers...

for instance, i need to be able to display a sentence such as

"There are X things in your queue"

where X is an integer

now, depending on the number of things, the grammar will be different.
 if there is only 1 thing, I need it to say "There is 1 thing...",
with 2 or more, it needs to read "There are 2 things..." and with 0
things, "There is nothing..."

now i could put all the code to handle this in my template, but that
would be ugly (and not DRY), or i could but in a helper and just call
the helper when I need to display that sentence correctly

def queue_title(things = 0)
  title = "There "
  case things
    when 0
      title += "is nothing"
    when 1
      title += "is 1 thing"
      title += "are #{things} things"
  title += " in your queue"

then in my view template

<%= title_for_queue(@things.size) ->

now a partial is a chunk of your view template that you want to either
reuse or use repeatedly.  candiates for partials are table rows, list
items, forms, etc.

so say i have a form that i want to use a few different views, i would
put it into a partial


<form ...>

and wherever i want to show this form i can call

<%= render :partial => "my_form" -%>

i suggest you also read the rails docs on helpers and partials.

hope this helps

70ca58d0e0e0eabbdb74d177417d09d7?d=identicon&s=25 (Guest)
on 2007-01-20 20:21
(Received via mailing list)
My rule of thumb is that if the rhtml is way to full of ERb <% %> tags,
I'll make a helper instead.
This topic is locked and can not be replied to.