Grails controllers repeated code for all actions

主宰稳场 提交于 2019-12-06 05:34:56

A simple solution is to put this code in a method and call it from each action

class exampleController{

  def action1 = {getModel()}

  def action2 = {getModel()}

  def action3 = {getModel()}

  def action4 = {getModel()}

  def action5 = {getModel()}

  private getModel() {
    def user = session.user    
    [user: user]    
  }
}

While this does involve some amount of repetition (invocation of the same method), it's a lot more obvious what's happening here. When debugging/testing a controller it's easy to forget about filters and interceptors, which can often lead to questions like

what the @**% is going on here?

I have a similar case, and I was modified the grails scaffolding for the controller's generator.

class MyClassController {

    def list = {
        ...
    }

    def show = {
        def eInstance = beanIfExist()
        ...
    }

    def edit = {
        def eInstance = beanIfExist()
        ...
    }

    def update = {
        def eInstance = beanIfExist()
        ...
    }

    def delete = {
        def eInstance = beanIfExist()
        ...
    }

    def beanIfExist = {
        def beanInstance = MyClass.get(params.id)
        if (beanInstance) {
            return beanInstance
        } else {
            flash.message = "Error, invalid record."
            redirect(action: "list")
            return null
        }
    }

}

It is my suggestion, now if do you need another that sent a data to view then you can use interceptors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!