Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Implementing a Rules DSL


[ 304 ]

if (account.mediaList[media.title] == null) {
def now = new Date()
account.points -= media.points
account.mediaList[media] = now + media.daysAccess
// Rewards only applied on first consumption
rewards.applyRewardsOnConsume(account, media)
}
}
def purchase = { account, media ->
rewards.applyRewardsOnPurchase(account, media)
account.points += media.points
account.spend += media.price
}
def upgrade = { account, newPlan ->
if (account.plan == "BASIC" && newPlan == "PLUS")
account.points += 130
if (account.plan == "BASIC" && newPlan == "PREMIUM")
account.points += 430
if (account.plan == "PLUS" && newPlan == "PREMIUM")
account.points += 300

rewards.applyRewardsOnUpgrade(account, newPlan)
account.plan = newPlan
}
def extend = {account, media, days ->
if (account.mediaList[media] != null) {
account.mediaList[media] += days
}
}
}

Testing with Spock

Finally, we can test to see if our reward scripts are being triggered as expected, by
writing a Spock test specification for it. Here, we can verify that each individual
reward that we have defined is being triggered. We do this by setting up
consumption, purchase, and upgrade scenarios that we expect to trigger
the reward.


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