Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Building a Builder


[ 260 ]

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

}

given:
def builder = new PoorMansTagBuilder20 ()

when:
builder.root {
level1{
level2 {
}
}
}

then:
"""<root>
<level1>
<level2>
</level2>
</level1>
</root>""" == output()

Once again, this is a simple implementation of a tag builder. We are making no
interpretation of the method tags that are being passed in, so for each createNode
call, all we do is output a tag with parameters and attributes if necessary. The
setParent call is not relevant to us because we are just streaming output to standard
output. We will see in the next example where we need to implement this. Finally,
the nodeCompleted call just closes the
tag.


Now, we can apply this builder to the same customers markup script that we did
before, as follows. The only change required is to instantiate PoorMansTageBuilder20
in place of the original builder class.


As a markup builder, this falls well short of the features in the Groovy
MarkupBuilder class, but it does show just how easy it is to put together a quick
builder to fit the need of the day. Now, let's consider what we've learned, and look
at building something a little more useful.


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