0

I want to override(extend) the redirect method of a grails 3 controller.

In grails 2 this was done by overriding the method via metaClass. See Override Grails redirect method

Since grails 3 this is not working anymore.

What I want to achieve: I want to manipulate the argument map that is passed to the redirect method of every controller I implemented (filtered by package name)

Or to be more specific: I want to add/change the mapping param based on some small logic

Bernhard
  • 444
  • 1
  • 4
  • 19

2 Answers2

3

I want to override(extend) the redirect method of a grails 3 controller.

You can simply override the method as per usual language rules...

class DemoController {

    // ...

    void redirect(Map m) {
        // do whatever you like here...
    }
}

If you want to invoke the original redirect method you can do that too but you will need to explicitly implement the Controller trait...

import grails.artefact.Controller

class DemoController implements Controller {

    void redirect(Map m) {
        // do whatever you like here before
        // invoking the original redirect...

        // invoke the original redirect...
        Controller.super.redirect m
    }
}
Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
  • The original question includes "a grails 3 controller" which implies you only want to do this in 1 controller. The approach I would use in that case is described above. If you wanted to apply this same method to numerous controllers, you have a number of other options, some of which also involve traits. – Jeff Scott Brown Jan 28 '18 at 23:22
  • Thanks For the answer Jeff. Sorry for not describing that more in detail. Your second solution goes more in the direction I imagined. I still need the normal behavior of the redirect - I just want to extend it. I want to override the redirect for every of my controller classes with the same functionality. In order to follow the DRY principle, I would create an abstract class that implements the Controller trait and let every of my controllers inherit that? – Bernhard Jan 30 '18 at 19:12
  • "In order to follow the DRY principle, I would create an abstract class that implements the Controller trait and let every of my controllers inherit that?" - That could work but I think putting that logic in a trait instead of an abstract class is a better idea. – Jeff Scott Brown Jan 30 '18 at 20:19
0

You can try AST transformation with Type Annotation and GroovyASTTransformation. For example: take a look at - groovy.transform.Sortable annotation which injects compareTo method using org.codehaus.groovy.transform.SortableASTTransformation

Mamun Sardar
  • 2,679
  • 4
  • 36
  • 44