Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Implementing a Rules DSL


[ 278 ]

This will output the string Hello, World! to the console. In other words, we have
managed to introduce a variable into this script called message that has the preset
value Hello, World.


Exploiting bindings in DSLs


There are numerous ways in which we can use bindings in our DSLs. In this section,
we will discover how to use closures in the binding to implement several different
DSL styles. We will also look at how simply adding properties to the binding can be
an effective way to augment a DSL with shorthand.


Closures as built-in methods

We can add any property to the binding. This includes properties of the type
Closure. If we add a closure to the binding then the binding variable can be
addressed as if it were a built-in method. Here we add a greet property to the
binding which acts as a greet method in the evaluated script.


def Binding binding = new Binding()

binding.greet = { subject ->
println "Hello, $subject!"
}

shell = new GroovyShell(binding)
shell.evaluate("greet 'World'")

Closures as repeatable blocks

We've seen how using a closure within the binding can give the impression of having
built-in functions in our DSL. We can also use closures in the binding to allow a
nested block structure to be represented in the DSL. Using this style, we can repeat
a block multiple times within a single script. This is useful when we have a DSL that
needs to define multiple instances of the same entity or logic within the same script.
Take the following script example:


block {
nestedBlock {
}
}
block {
nestedBlock {
}
}

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