All of the previous techniques for calling a closure rely on us having prior knowledge of a field or variable that contains a closure. This is fine for most straightforward applications of closures, but this book is about developing DSLs, so let's dig a little deeper.
Take the Grails application framework as an example. You can download Grails from http://grails.org/Download. Grails uses closures as a neat way of defining actions for its user interface controllers. No further configuration is required for the Grails runtime to be able to dispatch requests to an action:
class UserController { …. def login = { …. Login closure code } }
We can implement a login action for our user controller in Grails—simply by declaring a closure in the controller
class and assigning it to a field called login
. In the UI, Grails provides tags to automatically create a link that will dispatch to our login action:
<g:link controller="user" action="login">Login<...