Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you share common methods in different grails controllers?

Currently when I need to share a method like processParams(params) between different controllers, I use either inheritance or services. Both solution has some inconvenients :

  • With inheritance, you cannot use multiple inheritance which means that you need to have all of your controller utility methods in one place. And also, there is a bug in grails that does not detect any code changes in Base Controller classes in development mode (you need to restart the app)
  • With services, you don't have access to all injected properties like params, session, flush...

So my question is : is there any other way to use some common methods accessible for multiple controllers ?

like image 327
fabien7474 Avatar asked Nov 16 '10 15:11

fabien7474


1 Answers

One option I like is to write the common methods as a category, then mix it into the controllers as necessary. It gives a lot more flexibility than inheritance, has access to stuff like params, and the code is simple and understandable.

Here's a tiny example:

@Category(Object) class MyControllerCategory {     def printParams() {         println params     } }  @Mixin(MyControllerCategory) class SomethingController {      def create = {         printParams()         ...     }      def save = {         printParams()     } } 
like image 76
ataylor Avatar answered Sep 28 '22 04:09

ataylor