skip to Main Content

Grails Metaprogramming

With the extremely rapid rapid application development benefits provided by Grails,  It can be tempting to feel you have learned nearly everything you need to know by the time you’ve got your first web app up linked to a database with full CRUD facilities and error handling ready.  I’m sure you were as impressed with the speed of development as I was when I created my first Grails app.

At such a point it can be very tempting to just rush straight into your next project,  however you absolutely must continue your learning path and look over the excellent documentation  otherwise you be will missing out on some of the finer features provided by Grails and the Groovy language.

One feature I love and is the purpose of this article is Grails Metaprogramming.  It really makes a big difference for us Java programmers who can now add new functionality to already present classes very very quickly.

How many times have you thought oh I wish the String class had a truncate function built in for returning just a few characters of a long String with ellipses added if needed, or similar questions?

With MetaProgramming you can do just that, take the truncate() example ,   Apache Commons provide an abbreviate method in their StringUtils class which does the job perfectly, so if we could use that to do the work but also provide the ability to call it directly on  String class, ANYWHERE throughout our app, whether in GSP pages or controllers, services etc, all we need to do is dynamically add it to the String class in BootStrap.groovy like thus.

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 = {}
}


Another handy example that I’ve used frequently that comes to mind is a Date object when used to represent a date of birth.  There have been many times it’s been required that the age of the ‘person’ or whatever the date of birth belongs to, is also displayed and used.

So just like we added the truncate method to String objects we can likewise add an age() method to Date objects.

Date.metaClass.getAge = {
  new Date().year - delegate.year
}

Note in the above I am not defining expected parameters to be passed in as ‘delegate’ can always be assumed to be present, like ‘it’ in many cases.

So MetaProgramming, as you can see is a very powerful capability, limited by only our imagination as to what you can do yet can also easily be overlooked thanks to all the more immediately obvious benefits of Grails & Groovy.

Why not let us know what MetaProgramming additions you find you can’t live without

This Post Has 0 Comments

Leave a Reply

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

Back To Top