Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 11

[ 299 ]

RewardService provides three event hook methods: applyRewardsOnConsume,
applyRewardsOnPurchase, and applyRewardsOnUpgrade. These hook methods are
to be called in response to consume, purchase, and upgrade events in the system.
The hook methods take care of preparing the binding with the necessary closures
and binding variables, before performing a deferred invocation of the onConsume,
onPurchase, or onUpgrade closures that were stored earlier. The convenience
methods prepareClosures and prepareMedia set up some of the common
binding variables, which implement our built-in action methods and other
boolean shorthands.


class RewardService {
static boolean on_consume_provided = true
def static onConsume = {
on_consume_provided = false
}
static boolean on_purchase_provided = true
def static onPurchase = {
on_purchase_provided = false
}
static boolean on_upgrade_provided = true
def static onUpgrade = {
on_upgrade_provided = false
}

void prepareClosures (Binding binding) {
binding.onConsume = onConsume
binding.onPurchase = onPurchase
binding.onUpgrade = onUpgrade
binding.reward = { spec, closure ->
closure.delegate = delegate
binding.result = true
binding.and = true
closure()
}
binding.condition = { closure ->
closure.delegate = delegate

if (binding.and)
binding.result = (closure() && binding.result)
else
binding.result = (closure() || binding.result)
}
Free download pdf