Tuesday, March 10, 2009

Groovy Meta programing to help with names in grails

So in my new app I have several places where a user can enter a persons name. In most places they enter a first name and surname. But on one form they enter a full name. Now ideally i would like to have the first letter of the first name and surname capitalised. As you can't rely on users to do this and not wanting to punish them for not doing it then i decided to implement my own conversion.

Now in java i can imagine some crazy ways to do it. However probably the simplest in java would be to use the commons lang libs that have support for doing just that. (capitalize)

However i want to solve this in a "groovy way".

So after reading the groovy programming book I got some inpiration to use groovy meta-programming to solve the problem.

Groovy allows you to effectivly add new methods to java classes. In this case String. So on String i want to add two new methods: capitalizeFirstLetter and capitalizeAllFirstLetters. So to do this i just do this:

String.metaClass.capitalizeFirstLetter = {
return ("" == delegate) ? delegate : delegate[0].toUpperCase() + delegate[1..<(delegate.length())]
}

String.metaClass.capitalizeAllFirstLetters = {
return ("" == delegate) ? delegate : delegate.split(" ").collect{it[0].toUpperCase() + it[1..<(it.length())] }.join(" ")
}



Then when I want to use them i just do this:

assert "".capitalizeFirstLetter() == ""
assert "peter".capitalizeFirstLetter() == "Peter"
assert "peter delahunty".capitalizeAllFirstLetters() == "Peter Delahunty"



In Grails you just pop the metaClass definitions into your boostrap.groovy and they will be available all throughout grails.

Schweet...

2 comments:

tomCorbin said...

might be easier to use

delegate[1..-1]

if you can.

research paper writing help said...

I think Grails was previously known as 'Groovy on Rails'; in March 2006 that name was dropped in response to a request by David Heinemeier Hansson, founder of the Ruby on Rails framework