Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 176 ]

Running the preceding code will output the following text:


Class method this is : class Clazz


Closure this is : class ConsoleScript1


Closure Closure this is : class ConsoleScript1


Method Closure this is : class Clazz


Script this is : class ConsoleScript1


So, the rules for resolving this, owner, and delegate in the various contexts are:



  • In a class instance method, this is always the instance object. owner and
    delegate are not applicable and will be disallowed by the compiler

  • In a class static method, this, owner, and delegate references will be
    disallowed by the compiler

  • In a closure defined within a script, this, owner, and delegate all refer to
    the Script object unless delegate has been reassigned

  • In a closure within a method, this and owner refer to the instance object
    of the enclosing class; as will delegate, unless it has been reassigned to
    another object

  • In a script, this is the Script object, and owner and delegate are
    not applicable


How builders work


Earlier, when we looked at the MarkupBuilder code, the unfamiliar syntax must
have seemed strange. Now that we have an understanding of how the MOP and
pretended methods work, let's take a quick look again at some builder code and see
if we can figure out what might be happening. MarkupBuilder is derived from the
BuilderSupport class. When describing how MarkupBuilder works, I won't make a
distinction between BuilderSupport and MarkupBuilder. Most of the mechanisms
described here are in fact implemented by BuilderSupport and are shared with
other Builder classes:


def customers = builder.customers {
customer(id:1001) {
name(firstName:"Fred",surname:"Flintstone")
address(street:"1 Rock Road",city:"Bedrock")
}
customer(id:1002) {
name(firstName:"Barney",surname:"Rubble")
address(street:"2 Rock Road",city:"Bedrock")
}
}

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