Chapter 7
[ 181 ]
when:
BusinessService.isRemoteServiceLive()
then:
thrown NullPointerException
when:
BusinessService.metaClass.static.isRemoteServiceLive =
{ true }
def live = BusinessService.isRemoteServiceLive()
then:
notThrown NullPointerException
live == true
Dynamic method naming
We can use GStrings to name methods as we add or override them in a class. This
means that we can dynamically generate method names on the fly. In the following
example, we iterate all of the properties in the Customer class. We can exclude the
class and metaClass properties with the find operator it =~ /lass/ so that we
just add methods for the properties that we want:
class Customer {
int id
String firstName
String surname
String street
String city
}
given:
def c = new Customer()
c.properties.keySet().findAll { !(it =~ /lass/)}.each {
Customer.metaClass."idFor${it.capitalize()}" = { ->
delegate."$it".toString().toLowerCase().tr(' ', '_')
}
}
when:
def cust = new Customer(firstName:"Fred",
surname:"Flintstone",
street:"Rock Road",
city:"Bedrock")