smeeb
smeeb

Reputation: 29477

Grails controllers and inheritance/closures

Grails 2.4.4 here. All of my controllers were generated using the standard grails create-controller ... command:

class FizzController {
    def index() {
        // ...
    }
}

class BuzzController {
    def index() {
        // ...
    }
}

...etc.

At the top of each action method, in each controller, I need to call a method doSomething(String). This method needs to have access to redirect(...) so that it can redirect the user if need be. Ideally, I could create an abstract base controller class and have all my controllers extend it:

abstract class BaseController {
    void doSomething(String cmd) {
        if(cmd == 'Yee haw!') {
            redirect(controller: 'foo', action: 'baz')
            return false
        }
    }
}

class FizzController extends BaseController {
    def index() {
        String cmd = getCmdSomehow()
        doSomething(cmd)

        // ...etc.
    }
}

class BuzzController extends BaseController {
    def index() {
        String cmd = getCmdSomehow()
        doSomething(cmd)

        // ...etc.
    }
}

However I'm not sure Grails will allow this, since it's doing "Groovy magic" under the hood to make sure there is access to things like redirect(...) and render(...), etc. It would also be wonderful if I could put all this in a closure and just have it executed implicitly (without having to call doSomething() at the beginning of each and every controller action.

What is my best option/solution here? Please use a concrete code example!

Upvotes: 0

Views: 671

Answers (1)

Michal_Szulc
Michal_Szulc

Reputation: 4177

Use Filter instead:

class ExampleFilters {

   def filters = {

      logFilter(controller: '*', action: '*') {

         before = {
         }

         after = { Map model ->
         }

         afterView = {
         }
      }
   }
}

Upvotes: 4

Related Questions