Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Groovy, is there a way to know the name of a variable holding a closure?

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.

like image 332
Rich Sadowsky Avatar asked Jan 20 '23 00:01

Rich Sadowsky


1 Answers

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.

like image 117
Artur Nowak Avatar answered Jan 31 '23 05:01

Artur Nowak