Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 9

[ 233 ]

We can illustrate the same technique by using MarkupBuilder. The Markup class in
the following code snippet just declares a static closure named markup. Later on, we
can use this closure with whatever builder we want, by setting the delegate of the
markup to the builder that we would like to use:


given:
Markup.markup.setDelegate(new groovy.xml.MarkupBuilder())

when:
Markup.markup() // Outputs xml

then:
"""<customers>
<customer id='1001'>
<name firstName='Fred' surname='Flintstone' />
<address street='1 Rock Road' city='Bedrock' />
</customer>
<customer id='1002'>
<name firstName='Barney' surname='Rubble' />
<address street='2 Rock Road' city='Bedrock' />
</customer>
</customers>""" == output()

One-to-many


A one-to-many relationship applies when an instance of class such as
CustomerWithInvoice is associated with many instances of another class.
For example, a customer may have many different invoices in the system,
and an invoice might have a sale order object for each line on the invoice:


class CustomerWithInvoice {
String firstName
String lastName
static hasMany = [invoices:Invoice]
}

class Invoice {
static hasMany = [orders:SalesOrder]
}

class SalesOrder {
String sku
int amount
Double price
static belongsTo = Invoice
}
Free download pdf