views:

115

answers:

2

Hi,

My understanding is that there are two obvious places in a Grails app where one can do meta-programming:

  1. The init closure of Bootstrap.groovy
  2. The doWithDynamicMethods closure of a plugin

The meta-programming I'm referring to here should be visible throughout the metaprogramming, typical examples include adding (or replacing) methods of 3rd party classes.

String.metaClass.myCustomMethod = { /* implementation omitted */ }

The disadvantage of (1), is that the metaprogramming won't be applied when the application is dynamically reloaded. The disadvantage of (2) is that I need to create and maintain an entire plugin just for the sake of a little metaprogramming.

Is there a better place to do this kind of metaprogramming?

Thanks, Don

+1  A: 

Depending on your use case, Groovy AST transformations are a third option. AST transformation are modifications of the bytecode at compile time. They are available since Groovy 1.6 and have been improved a lot in Groovy 1.7. Esp. ASTBuilder is a very elegant way.

Be aware that using AST within Grails might require some modifications to the build. The classes performing the AST must be compiled before the classes that are subject to AST. This could be easily done by hooking into the "CompileStart" event in scripts/_Events.groovy and precompile the Transformation first.

Stefan
Thanks for the suggestion, but if I just want to add a few methods to a class, this sounds like overkill.
Don
A: 

Check out the Delegating MetaClass, it's part of groovy and makes your metaclass changes part of the metaclass that's used on every instance of that class right from the start. It operates on a simple convention and even works outside of grails.

Ted Naleid
My question is about where in a Grails app should I apply metaprogramming, not how to do the metaprogramming itself.
Don
Right, I understand that. That's why I'm suggesting that the place that you should do it is within a convention named class that makes your changes/additions available throughout the grails application and don't suffer from the problems of putting it in BootStrap, or some other "init" method that might or might not have been called by the time you need it.
Ted Naleid