Monday, July 25, 2011

grails - export plugin, at dynamically more attributes

What is this about?

currently I'm writing on a little tech study application, called times. Which can be accessed here

This application is a very simplistic timetracker, but allows me to play with some api's I normally don't use or to simply test some grails functions.

Right now I had a simple idea.

I want to export all my data, using the grails export plugin, without cluttering my database model with dozens of attributes, which will never be queried. I also did not want to create pojo's, just for the export. Instead I decided to play a bit with the EMC MetaClass again and see if, we can do this on the fly.


def exports = []

def fields = ["name","organization","project","beginDate","endDate","timeSpend"]
def labels = ["name":"Name","organization":"Organization","project":"Project","beginDate":"Start","endDate":"Finished","timeSpend":"Durations (s)"]
Task.list().each {Task t ->
if (t.endDate != null) {
t.metaClass.timeSpend = (t.endDate.time - t.beginDate.time)/1000

exportService.export(params.format, response.outputStream, exports,fields,labels, [:], [:])

this registers the attribute 'timeSpend' to the lifespan of the Task instance 't'. Which is only be required during the export.

The important line is

t.metaClass.timeSpend = (t.endDate.time - t.beginDate.time)/1000

Short, it can simplify your life a bit and reduces the need of introducing a pojo, just to export data or to permanently add this object to your database. Specially since it's a calculated value and can be regenerated on the fly.

No comments:

Post a Comment