Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 11

[ 295 ]

...
}
...
}
onUpgrade = {
...
}

By using this structure for the DSL, the loading and evaluating of the script simply
causes the three closure assignments to be executed. On completion of the evaluation
of the script, there will be three closure variables in the binding, which contain the
reward logic. This small change to the structure means that we can now load and
evaluate the script just once on initialization, and invoke the specific rewards for
consume, purchase, and upgrade as required.


Here we see how we can use GroovyShell to defer execution of a closure block:


def binding = new Binding()
binding.saved = {
}

binding.deferred = { closure ->
closure.delegate = delegate
closure()
}

def shell = new GroovyShell(binding)
shell.evaluate(
"""
saved = {
println "saved"
deferred {
println "deferred"
}
}
"""
)
storeSaved = binding.saved
Free download pdf