Implementing a Rules DSL
[ 276 ]
Groovy bindings
Every Groovy script has an associated binding object. The binding is where instances
of variables referenced within the script are stored. The binding is an instance of the
class groovy.lang.Binding, and we can access it in any script by referencing the
built-in variable binding, as the next example will show.
When we reference a previously undeclared variable in a script,
Groovy creates an instance of the variable in the binding. On
the other hand, variables that are defined within the script are
considered local variables and are not found in the binding. The
latter provides a convenient placeholder where Groovy can store
these variables. This also presents the DSL with an opportunity.
By manifesting variables in the binding, we can manipulate the
script with predefined values. By adding a closure to the binding,
we can provide built-in methods for the DSL.
In the following example, when we reference a new variable named count in a
script, we see how that variable is stored in the binding. If we explicitly declare the
variable local with def, we can use both variables interchangeably, but only count
is stored in the binding.
count = 1
assert count == 1
assert binding.getVariable("count") == 1
binding.setVariable("count" , 2)
assert count == 2
assert binding.getVariable("count") == 2
def local = count
assert local == 2
try {
binding.getVariable("local")
assert false
} catch (e) {
assert e in MissingPropertyException
}
http://www.ebook3000.com