e;

making it more convenient to be plural

Posted Friday, May 23, 2008, at 10:17PM by Eric Richardson

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 —



Eric Richardson lives in Los Angeles, California, and is generally interested in the intersection between technology, community and news.

He started blogdowntown, an online news site for Downtown Los Angeles, and today works in digital media for Southern California Public Radio.



On This Date