I'm wondering how to call a closure from a closure that's being used with a DSL. For example, let's take the RestBuilder
plugin for Grails.
Imagine I have several blocks in a row like:
rest.post("http://my.domain/url") {
auth(username, password)
contentType "text/xml"
body someContent
}
... where the only thing changing is the someContent
. It gets repetitive to call auth
and contentType
and body
each time. So I'd like to do something like:
def oauth = [clientId: 'c', clientSecret: 's']
def withAuth(Closure toWrap) {
Closure wrapped = { it ->
auth(oauth.clientId, oauth.clientSecret)
contentType "text/xml"
toWrap.call()
}
return wrapped
}
rest.post("http://my.domain/url") (withAuth {
body someContent
})
Now, I'd like wrapped
and toWrap
to have access to auth
and contentType
as defined in the RestBuilder
DSL. Is there a way I can do this by setting owners, delegates, or suchlike?
(Note: I understand in the example above that I could just declare a function that takes a URL + content as argument, and just call rest.post
within the function. My question is more general -- I'm looking to understand the language, and for functional techniques I can apply more broadly.)