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:
might be easier to use
delegate[1..-1]
if you can.
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
Post a Comment