Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 10

[ 251 ]

The root() method creates the initial tree map and inserts a root element into it. We
can nest as many levels deep as we like with the node() method as it will remember
its parent node and add sub nodes to it. The leaf() method is the only one to take a
value and it does not expect to be passed a closure, as it will create the leaf elements
in the tree structure:


def current
def root (Closure closure) {
def tree = [:]
def root = [:]
tree["root"] = root
def parent = current
current = root
closure.call()
current = parent
return tree
}

def node (key, Closure closure) {
def node = [:]
current[key] = node
def parent = current
current = node
closure.call()
current = parent
}

def leaf (key, value ) {
current[key] = value

}

given:
// pseudo builder code
def tree = root {
node("sub-tree-1") {
leaf "leaf-1", "leaf object 1"
}
node ("sub-tree-2"){
node ("node-1"){
leaf "leaf-2", "leaf object 2"
}
}
Free download pdf