May
23

making it more convenient to be plural

Published: Friday, May 23, 2008, at 10:17PM

Hello again neglected blog...

Ever since the April 1st launch of the new blogdowntown code, there's been a sloppy little bug that's bothered me, but not quite been bad enough to address. When putting comment counts on stories, I got sloppy and wrote:

<%= thumbnail.comments.length %> Comments

instead of being proper and making sure account for the singular case. Bottom-line: the conditional is ugly. I didn't want to have to write this everywhere:

<%= 
  story.comments.length.to_s + " " +  
  (story.comments.length == 1) ? "Comment" : "Comments" 
%>

So tonight I finally made the fix, but did it in a way that doesn't assault my senses.

I figure the number knows whether it equals one or not, so why can't I just ask it to decide my case for me?

class Integer
  def pluralize(term)
    if self == 0
      n = (term[0] >= 65 && term[0] <= 90) ? "N" : "n"
      return "#{n}o #{Inflector.pluralize(term)}"
    elsif self == 1
      return "#{self.to_s} #{term}"
    else
      return "#{self.to_s} #{Inflector.pluralize(term)}"
    end
  end
end

I plopped that in application.rb, and now I can do fun things like:

1.pluralize("Comment") # "1 Comment"
5.pluralize("Comment") # "5 Comments"
0.pluralize("Story") # "No Stories"
0.pluralize("story") # "no stories"

I don't have the situation where I need case determined on any words that Rails' default Inflector rules would bork on, but if I did I assume I could just define them the standard way.

Comments

1
Michael Economy writes:

Rails has: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M001728

but the "no comments" thing is a bit interesting

# on Jun.26.2008 AT 10:02 AM
2
e; writes:

Yeah. I looked at that, but really liked the concept that I could call the function straight on the number, instead of having to pass both to a helper. I'm pretty sure I borrowed the call to Inflector straight from that function.

# on Jun.26.2008 AT 02:19 PM

Your Comment:

YOUR INFORMATION:
Name:
Email:
URL:
  • Comments should be on the topic of the post or they will be removed.
  • Use the live preview below to see how your comment will look before posting.
  • Keep it civil. If you're attacking people instead of arguments, or being overly profane, expect your comment to get deleted.

FORMATTING BASICS:

eWorld uses Markdown formatting.

_Italics_
__Bold__
<http://url.to.link>
[link text](http://url)

COMMENT:

Preview

Start typing...