Saturday, September 27, 2014

GRAILS Custom Codec Example

All custom codec must be in grails-app/utils folder in any package.
Suppose I first created a package named 'pritom.kumar.codecs'.
Then created a groovy (not other type of class) class inside the package such named 'UpperCodec'.groovy
Class name must be end with 'Codec'.
My custom codec groovy class look like this:
package pritom.kumar.codecs

/**
 * Created by pritom on 05/09/2014.
 */
class UpperCodec {
    static encode = { target ->
        return target != null && target instanceof String ? target.toString().toUpperCase() : target
    }
}
Now you can use this as code in controller, service, other java or groovy classes, views and other places like this.

println "i am pritom kumar".encodeAsUpper();

Will print the following:

I AM PRITOM KUMAR

Basically you can do various things using custom codec.

No comments:

Post a Comment