The title may be misleading. What I really want is to know the name of a closure within a controller. But closures in Groovy are always anonymous, so there is no name of the closure itself. But the closure is assigned to a variable, and I'm wondering if I can get the name of that variable. Perhaps an example will help. In a Grails controller imagine I have the following:
def get_data = {
Map results = [ 'errorCode' = -1, 'method' : 'get_data' ]
...
render results as JSON
}
In the Map called results there's an element called 'method' that I want to assign to the name of this closure (or variable holding the closure to be more precise). Is this possible? The idea here is I want to generalize the results map and want to automatically populate an element called 'method'. Instinctively it feels like this should be possible but I haven't found any similar use cases that illustrate how. Any help much appreciated.
I don't think that you can get name of the variable in the general case. This is only a reference, and the closure can be assigned to many of them.
It is very simple, however, to get name of the current action in the controller code:
def get_data = {
def results = ['method': actionName]
}
See documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With