Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Implementing a Rules DSL


[ 282 ]

Here we declare two named closures: setup and teardown. We can now provide
default implementations of setup and teardown in the runtime that we use to load
and evaluate this script:


def binding = new Binding()
binding.setup = {
println "Setup block is missing"
throw new Exception("Setup block is missing")
}

binding.teardown = {
println "Teardown block is missing"
throw new Exception("Teardown block is missing")
}

def shell = new GroovyShell(binding)
shell.evaluate(
"""setup = {
'setup called'
}
teardown = {
'teardown called'
}
"""
)

setup = binding.setup
assert setup() == 'setup called'
// ... do something now and save teardown closure for later
teardown = binding.teardown
assert teardown() == 'teardown called'

For brevity, in some of the following examples, we will use
GroovyShell to evaluate our DSL scripts from GString. In most
real life DSL scenarios, you will want to externalize your DSL code.
GroovyShell can also be used to load and evaluate a script from a file.

An exception will be thrown if either setup or teardown has not been provided. This
is a useful tactic to use to ensure that one and only one block is executed from the
DSL. It also gives us control over the timing of when the blocks are actually executed.


http://www.ebook3000.com
Free download pdf