9

I have a case where I need to use pluralize to properly spell something. However, I need to render the html like so:

<span>1</span> thing

or,

<span>3</span> things

I could write a helper method, but I'm just making sure there isn't something in the box to do this.

Tim Sullivan
  • 16,808
  • 11
  • 74
  • 120
  • 1
    While I have agonized over this sort of thing in the past myself, I have come to believe that context sensitive pluralization is over kill. Unless you are literally generating prose, I find "1 things" or "1 thing(s)" perfectly acceptable. – Chris Noe Feb 03 '09 at 16:58
  • 1
    Attention to detail matters. – Tim Sullivan Jun 21 '13 at 06:23

2 Answers2

6

This uses the Rails class TextHelper which uses Inflector to do the pluralization if needed.

def pluralize_with_html(count, word)
  "<span>#{count}</span> #{TextHelper.pluralize(count, word)}"
end
Lolindrath
  • 2,101
  • 14
  • 20
  • This certainly works based on what I asked for, but I think the helper method I posted gives more flexibility to the designer in general. Thanks! – Tim Sullivan Feb 03 '09 at 17:22
  • I'll have to invoke YAGNI on that comment and say to refactor if you find another use. – Lolindrath Feb 03 '09 at 23:39
4

In the interim, I've created this helper method, because it looks like there isn't what I'm looking for:

def pluralize_word(count, singular, plural = nil)
  ((count == 1 || count == '1') ? singular : (plural || singular.pluralize))
end

It's essentially identical to the pluralize method, except that it removes the number from the front. This allows me to do this (haml):

%span.label= things.size.to_s
%description= pluralize_word(things.size, 'thing')
Tim Sullivan
  • 16,808
  • 11
  • 74
  • 120