views:

403

answers:

3

When persisting domain objects using Grails/GORM I frequently find myself wondering why a save() call fails.

This can easily be solved by adding the logic:

if (!o.save()) {
    o.errors.allErrors.each { println it }
}

However, adding this everywhere I do a .save() adds a lot of duplicate code. In the spirit of DRY I'd like to configure Grails/GORM to automatically print any save-errors to the console (stderr). Is that possible? If not, how do I extend GORM to make it possible?

A: 

This isn't the cleanest looking, and there is probably a better, groovier way to do this. Based on looking here I put together this code that might be something you could expand and use:

class Book {
   void printTitle(){ println "The Title" }
}

Book.metaClass.customPrintTitle << {-> 
    println "changin ur class"
    printTitle()
}

def b = new Book()

b.customPrintTitle()
codeLes
+3  A: 

Solution:

Object.metaClass.s = {
    def o = delegate.save()
    if (!o) {
        delegate.errors.allErrors.each {
            println it
        }
    }
    o
}

This adds a method called s() that will call save() and print any errors.

knorv
That is a nice expansion of the answer I provided. Glad you solved it.
codeLes
This will add s() to all objects, not just domain objects. To only add it to domain objects, I think you need to do the metaprogramming in the doWithDynamicMethods closure of a plugin
Don
A: 
Object.metaClass.s = {
def o = delegate.save()
if (!o) {
    delegate.errors.allErrors.each {
        println it
    }
}
o

}

Where do you put this code? Do you put it inside BootStrap.groovy inside the

def init = { servletContext -> ... }

method?

peter_pilgrim
peter_pilgrim: Exactly so. Please note that you've written an "answer" while you probably meant to do a comment or post a new question.
knorv