SuprF1y
SuprF1y

Reputation: 100

Move boilerplate code out of controller

I'm literally just starting out with grails and just generated some scaffolding. There seems to be some pretty generic code here that will be repeated in every controller.

  1. the test for whether the get() was successful
  2. the optimistic locking check

How would you recommend removing this from the controller? Ideally I would like to just do a

def personInstance = Person.get(id)

and then have a single exception handler do for every controller what is by default generated in each and every controller.

  def update(Long id, Long version) {
    def personInstance = Person.get(id)
    if (!personInstance) {
        flash.message = message(code: 'default.not.found.message', args: [message(code: 'person.label', default: 'Person'), id])
        redirect(action: "list")
        return
    }

    if (version != null) {
        if (personInstance.version > version) {
            personInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                      [message(code: 'person.label', default: 'Person')] as Object[],
                      "Another user has updated this Person while you were editing")
            render(view: "edit", model: [personInstance: personInstance])
            return
        }
    }

Upvotes: 3

Views: 176

Answers (2)

wwwclaes
wwwclaes

Reputation: 1152

Have a look at A Pattern To Simplify Grails Controllers, it proposes a Groovy pattern for this stuff. Let us know if you come up with a nice solution, I'm about to do something similar myself.

Upvotes: 1

practical programmer
practical programmer

Reputation: 1648

If you want to change default scaffolding for the controller, just issue "grails install-templates" command. A lot of files will be created in src/templates folder. And one of those is "src/templates/scaffolding/Controller.groovy"

Then just modify "update" function to the format which you need, and generate-controller again for your domain classes.

Still, you should consider if you really don't want to use optimistic/pessimistic locking, as this makes your application somehow not transactional.

Upvotes: 2

Related Questions