Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 10

[ 253 ]

indent--
indent.times {print " "}
println "</${name}>"
}
}

This is a simple case that we are using just to illustrate the mechanism. Although the
technique works for simple cases, extending it to implement a more complete tag
builder will rapidly result in complex and hard to maintain code.


methodMissing

Since Groovy 1.5, an alternative to invokeMethod was provided. The
methodMissing mechanism differs slightly from invokeMethod, as it is only called
when a method call fails to be dispatched to any concrete method. To update the
PoorMansTagBuilder class for using methodMissing instead of invokeMethod, all
we need to do is replace the method name that we declare:


class PoorMansTagBuilder {
int indent = 0
def methodMissing(String name, args) {
indent.times {print " "}
println "<${name}>"
indent++
args[0].delegate = this // Change delegate to the builder
args[0].call()
indent--
indent.times {print " "}
println "</${name}>"
}
}

given:
def builder = new PoorMansTagBuilder ()

when:
builder.root {
level1{
level2 {
}
}
}
Free download pdf