Chapter 7
[ 167 ]
Here we create a CustomerPrinter class that pretty prints a customer object.
We can then make use of this class's methods in a use block and apply them to
a Customer object:
class Customer {
int id
String firstName
String surname
String street
String city
}
class CustomerPrinter {
static void prettyPrint(Customer self) {
println "Customer has following properties"
self.properties.sort { it.key }.each {
if (it.key != 'prettyPrint' && it.key != 'class')
println " " + it.key + ": " + it.value
}
}
}
given:
def fred = new Customer(id:1001,firstName:"Fred",
surname:"Flintstone",
street:"1 Rock Road",city:"Bedrock")
def barney = new Customer(id:1002,firstName:"Barney",
surname:"Rubble",
street:"2 Rock Road",city:"Bedrock")
def customerList = [ fred, barney]
when:
use (CustomerPrinter) {
for (customer in customerList)
customer.prettyPrint()
}
then:
"""Customer has following properties
city: Bedrock
firstName: Fred