Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 12

[ 331 ]

constructorStatement
)
classNode.addConstructor(constructorNode)
}

Most of the preceding code should be familiar to you. The one aspect we have
not come across before is the construction of the parameter declaration for the
constructor. Earlier in the chapter, I mentioned the difficulties in generating a map as
a parameter to a method. The parameter class constructor requires a ClassNode as its
first argument and the recommended method for creating one of these for an existing
object is to use the ClassHelper.make method. Unfortunately, this does not seem
to work successfully when you try to create a ClassNode for a generic type such
as map.


The same issue occurred when trying to generate the event methods in the following
code. The compromise I settled on was to declare these parameters as an object but to
treat them as map. Here we create block statements for each event method with the
lines of code from the class pattern:


def buildClientEventMethods() {
for (event in model.events) {
def blockStatement = new BlockStatement( [
new ExpressionStatement(
new MethodCallExpression(
new VariableExpression("this"),
new ConstantExpression("restoreSession"),
new ArgumentListExpression(
[
new ConstantExpression(className),
new VariableExpression("sessionData")
]
)
)
),
new ExpressionStatement(
new MethodCallExpression(
new MethodCallExpression(
new VariableExpression('session'),
new ConstantExpression('getPage'),
ArgumentListExpression.EMPTY_ARGUMENTS
),
new ConstantExpression("${event}"),
new ArgumentListExpression(
new VariableExpression('event')
)
Free download pdf