I am looking for ways on how to cleanup my Grails controller code. In various controllers i more or less have the same logic..
- get the object
- check if it exists
- etc..
Is there a suggested way on making controller actions reuse common code?
— solution —
All answers to the question have contributed to the solution we have implemented.
We created a class that is used in our controllers using the Mixin approach. One of the methods that the mixin exposes is the withObject method. This method takes the domainname from the controller and uses this a base for the method. This behaviour can be overridden of course!
def withObject(object=this.getClass().getName()-"Controller", id="id", Closure c) {
assert object
def obj = grailsApplication.classLoader.loadClass(object).get(params[id])
if(obj) {
c.call obj
} else {
flash.message = "The object was not found"
redirect action: "list"
}
}
So all answers have contributed to the solution! Thanks a lot!
I always pull out this blog post when this question comes up:
http://mrpaulwoods.wordpress.com/2011/01/23/a-pattern-to-simplify-grails-controllers/
Basically you have a private helper for various domains in your controllers.
The way you code the getter is very flexible and a typical use for me (that is not covered in the blog) is for editing etc.
I normally code this way (i like the pattern for its clear division and readability):
With my getter helper being:
I do think that the mixin method (very similar to the ‘extend a common abstract controller’ way) is nice too, but this way gives two advantages:
In the view I bind to edit() I just put an
id="${issue.id}"in the<g:form>and it works seamlessly.