5

I have a Trait defined like so:

@Enhances(ControllerArtefactHandler.TYPE)
trait NullCheckTrait {
   def nullCheck(def object) {
      // code here
   }
}

When I call nullCheck(foo) from my controller, I get the No signature of method exception. If I implements NullCheckTrait on the controller, it works fine. I've read that @Enhances will only work if I create a grails plugin and put the trait there. I'm curious if this is a known issue and if there is a way to get the @Enhances to work from the same grails application as the controller.

Gregg
  • 34,973
  • 19
  • 109
  • 214

2 Answers2

3

No there is no way to get around this since @Enhances classes need to be on the classpath before compilation. For example say your controller class is compiled first and then later your trait then the trait won't be applied, and since there is no way to control compilation order this will remain an issue.

The only other way this could be done in the same project is to setup an additional source set in Gradle, see:

How do I add a new sourceset to Gradle?

Community
  • 1
  • 1
Graeme Rocher
  • 7,985
  • 2
  • 26
  • 37
  • @Graeme Rocher does this still stand valid ? there's already an ast sourceset and puting the transformations under src/ast works even in the same project, without needing extra plugin just for AST, see my answer below – Sudhir N Jul 05 '17 at 14:18
2

There's one more solution which does not need you to create a custom additional source set.

grails gradle plugin, by default comes with a sourceset named ast which gets compiled before any main sourceset. so you can put your Trait in ast sourceset and that will get applied to artefacts even in the same plugin/project.

Here's how your project structure should be

 src
  +
  +--+ast
        +
        +--+groovy
                 +
                 +--+MyAwsomeTrait.groovy

And this will get compiled before the classes in src/main sourceset and grails will pick your sourceset and apply it.

update: Grails configures the ast sourceset only for plugin projects and not application. Here I wrote a blog entry about how to create an AST sourceset for applications

Sudhir N
  • 4,008
  • 1
  • 22
  • 32
  • Update: The above solution works for plugin projects only and not for application projects, see issue https://github.com/grails/grails-core/issues/10717 – Sudhir N Jul 05 '17 at 16:21