I've been programming away with Grails for a fair bit of time now but have only touched the surface with the meta programming capabilities provided by Groovy.
Aside from all the dynamic capabilities we are provided with, e.g. DomainClass.FindBySomeField I didn't realise we can really make use of these capabilities ourselves until recently when I was about to create a static method in a utility class to abbreviate strings. I use grids a lot and some of the string data I am showing in certain columns can be very long, so I wanted to show the first 50 characters followed by "..." if it exceeds 50 characters.
I found a little snippet of code that demonstrated the ability to add new methods to the String class itself, completely bypassing my need to create a method in a utility class, which makes the code much easier to follow as I could then just call truncate() method on the string I wanted to manipulate.
How did I do this? Very very simply..
We add the new method declaration within the init method in BootStrap.groovy!
This certainly opens up possibilities I wouldn't have considered before, and just goes to show the more you use grails the more times you'll smile and think, hey that makes things 'easier'!
Check out the original source for this tip and other tips over at my blog : http://www.tucanoo.com/grails-metaprogramming
Aside from all the dynamic capabilities we are provided with, e.g. DomainClass.FindBySomeField I didn't realise we can really make use of these capabilities ourselves until recently when I was about to create a static method in a utility class to abbreviate strings. I use grids a lot and some of the string data I am showing in certain columns can be very long, so I wanted to show the first 50 characters followed by "..." if it exceeds 50 characters.
I found a little snippet of code that demonstrated the ability to add new methods to the String class itself, completely bypassing my need to create a method in a utility class, which makes the code much easier to follow as I could then just call truncate() method on the string I wanted to manipulate.
How did I do this? Very very simply..
We add the new method declaration within the init method in BootStrap.groovy!
Code:
import org.apache.commons.lang.StringUtils
class BootStrap {
def init = { servletContext ->
// modify string objects to add new truncate method
String.metaClass.truncate = {len ->
return StringUtils.abbreviate(delegate, len) ?: ''
}
}
def destroy = {
}
}
This certainly opens up possibilities I wouldn't have considered before, and just goes to show the more you use grails the more times you'll smile and think, hey that makes things 'easier'!
Check out the original source for this tip and other tips over at my blog : http://www.tucanoo.com/grails-metaprogramming