Technipelago AB

Technipelago Blog Stuff that we learned...


Add method on String to truncate long texts nicely

Publicerad den 17 nov 2008

I had several domain classes with long text content that I wanted to display just a summary of on the screen, especially in lists columns, etc.. I first added a getIntro(int numChars) method on domain classes with long strings, and used them when appropriate.

But I soon realised that I violated the DRY principle (Dont Repeat Yourself) with getInto() methods all over the place. I could have put the method in a base class but my text properties did not have the same name in all domain classes, so that was complicated.

I think I found a much better solution. I removed all those methods and added a getIntro(int) method to String and GString in BootStrap.groovy.


import org.apache.commons.lang.StringUtils

String.metaClass.intro = {len ->
  return StringUtils.abbreviate(delegate, len) ?: ''
}

GString.metaClass.intro = {len ->
  return StringUtils.abbreviate(delegate.toString(), len)
}

Now if I want a short introduction of a long text displayed somewhere I can just do like this:


def longText = "This is a long text that can mess upp the gui if it is displayed in its full length"
longText.intro(20).encodeAsHTML()

The result will be: This is a long text…

Adding new methods to existing classes is a really nice feature in Groovy!

Tags: groovy grails


« Tillbaka