Building a Builder
[ 252 ]
}
expect:
tree == [
root: [
"sub-tree-1": [
"leaf-1": "leaf object 1"
],
"sub-tree-2": [
"node-1": [
"leaf-2": "leaf object 2"
]
]
]
]
Pretended methods
Many Groovy builders rely on the ability to describe arbitrarily named elements.
When we make use of markup builders to generate XML, we need to be able to insert
whatever tag names are required to conform to the schema that we are using. Given
that elements are created in method calls, we also need to be able to make arbitrarily
named method calls during the markup process.
With Groovy, we can respond to methods that don't exist as concrete methods of a
class. The term we use for these types of methods is pretended methods. Groovy
provides two means for implementing a pretended method.
invokeMethod
The PoorMansTagBuilder class that we covered in Chapter 5, Groovy Closures,
uses invokeMethod as a means of pretending methods. The PoorMansTagBuilder
class works by handling all method calls to the builder, and invoking the closure
argument manually. With invokeMethod, we can respond appropriately to any
arbitrary method call. In this case, we output the appropriate XML tags:
class PoorMansTagBuilder {
int indent = 0
Object invokeMethod(String name, Object args) {
indent.times {print " "}
println "<${name}>"
indent++
args[0].delegate = this // Change delegate to the builder
args[0].call()
http://www.ebook3000.com