I am overwriting the redirect method of every controller I wrote. I did that because
a) I need to set some variables before the redirect is actually executed
b) I want to do that globally because it is the same code for every controller and I want to be DRY
I did this in the bootstrap because it is executed when the server starts.
Code:
grailsApplication.controllerClasses.each() { controllerClass ->
if (controllerClass.fullName.startsWith("my.package")){
def oldRedirect = controllerClass.metaClass.pickMethod("redirect", [Map] as Class[])
controllerClass.metaClass.redirect = { Map args ->
// pre-redirect logic
args.put("some", "property")
oldRedirect.invoke delegate, args
// post-redirect logic
}
}
}
Here is the problem:
When I am developing, I use the reloading feature / just in time compiler which recompiles the file without the need to restart the server. In this case the controller is rebuilt and as a result the overwritten redirect method is lost.
Here is the question:
Is there a callback / another way to find out when a class is recompiled in runtime? I would love to check if a controller was rebuild and then overwrite the redirect method again!
Yes, break this functionality out into a plugin and you can then observe reloading of classes and re-apply your changes. The documentation goes into great detail on participating in auto reload events.
This would be the cleanest, and most proper way to accomplish what you are looking to do.