Injecting Method to trim string length on gsp pages

03 / May / 2010 by Aman Aggarwal 3 comments

Restricting the length of a string on gsps is a common scenario in most of our projects.
Groovy’s metaprogramming magic made it too simple for me. I added the following lines of code to Bootstrap.groovy:

Object.metaClass.trimLength = {Integer stringLength ->

    String trimString = delegate?.toString()
    String concatenateString = "..."
    List separators = [".", " "]

    if (stringLength && (trimString?.length() > stringLength)) {
        trimString = trimString.substring(0, stringLength - concatenateString.length())
        String separator = separators.findAll{trimString.contains(it)}?.min{trimString.lastIndexOf(it)}
        if(separator){
            trimString = trimString.substring(0, trimString.lastIndexOf(separator))
        }
        trimString += concatenateString
    }
    return trimString
}

Now, for an instance of class Person:

class Person {
    String name

    String toString(){
        return name
    }
}

Person person = new Person(name: "Aman Aggarwal")

I can simply write this code in gsp:

person.trimLength(10)

which renders output:

Aman...

Hope it helps.

~Aman Aggarwal
aman@intelligrape.com

http://www.tothenew.com/blog/

FOUND THIS USEFUL? SHARE IT

comments (3)

  1. Farid

    Thanks Aman. This blog really made my life easy in my current project. I am really surprised that groovy does not provide something of this sort out of box.

    Reply
  2. Lavern Montezuma

    Please let me know if you’re looking for a article writer for your weblog. You have some really great articles and I think I would be a good asset. If you ever want to take some of the load off, I’d love to write some material for your blog in exchange for a link back to mine. Please blast me an email if interested. Thank you!

    Reply
  3. Hubert Klein Ikkink

    We used the following approach on our project:

    // File: Bootstrap.groovy
    import org.apache.commons.lang.StringUtils

    def init = { ctx ->
    String.mixin StringUtils
    }

    Now we can use “abcdefg”.abbreviate(6) to get ‘abc…’
    What happened? We added all static methods from StringUtils with a first argument of type String to the String class, so we can use them in our application.

    Reply

Leave a Reply to Hubert Klein Ikkink Cancel reply

Your email address will not be published. Required fields are marked *