Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 11

[ 277 ]

Most of the examples we have encountered in the book are written to be
run as Spock tests. The next few examples in this chapter are best run
from the command line. You could also run this in the Groovy console
but the Groovy console maintains a single binding object. So, each time
you execute a script from the buffer, you are inheriting objects that were
probably stored there during the previous runs. The examples in this
chapter all assume a clean binding, so running successive examples in
groovyConsole will lead to unpredictable results.

The power of bindings with regard to their use in DSLs comes from the fact that we
can add a variable to the binding on the fly. If count does not exist as a variable in
the script, then it can be added by a call to setVariable, as follows:


binding.setVariable("count" , 1)

assert binding.getVariable("count") == 1

binding.setVariable("count" , 2)

assert binding.getVariable("count") == 2

The binding class also implements the property access APIs, such as setProperty,
getProperty, and getProperties. This means that the binding will allow bean-like
access, including the use of the subscript operator.


binding.count = 1

assert binding.getProperty("count") == 1

binding.setProperty("count" , 2)

assert binding.count == 2

These examples might look like a clumsy way of getting and setting variables in
a script, but the binding becomes really useful when we execute a script that we
have loaded. Here we set a property message in the binding and then use the
GroovyShell class to execute a script snippet that uses it.


def Binding binding = new Binding()

binding.message = "Hello, World!"

shell = new GroovyShell(binding)

shell.evaluate("println message")
Free download pdf