String#Nameize

This morning we had an email from someone who wanted us to capitalize their name because they had not done it at signup.  That’s fine and all, but this is one of those things we’re going to see again.  Normally you’d just slap a .capitalize on the string and call it a day.  Unfortunately with Irish names, you run into a problem because capitalize doesn’t capitalize those types of names properly.  I wrote a quick function to extend the String class in Ruby that will help get around this problem.

class String
  # Extension of the string class to properly handle camel names
  # Should be used on pieces of names, not full names.
  def nameize
    # If they took the time to capitalize their name then let's just jump out
    if self.match(/\A[A-Z]/)
      return self
    else
      name = self.downcase
    end
    # Let's now assume that they were lazy...
    return case
    when name.match(/^mac/)
      name.capitalize.gsub(/Mac/, "").capitalize.insert(0, "Mac")
    when name.match(/^mc/)
      name.capitalize.gsub(/Mc/, "").capitalize.insert(0, "Mc")
    when name.match(/^o\'/)
      name.split("'").each{ |piece| piece.capitalize! }.join("'")
    else
      name.capitalize
    end
  end
end

I know it’s not perfect, but it should handle most oddly capitalized names.  Let me know what you think in the comments or on Twitter or whatever and definitely give me any changes you think should be in there.

Posted in Code, Software Development, ruby at October 24th, 2008. Trackback URI: trackback
Tags: , ,

No Responses to “String#Nameize”

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>