Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Implementing a Rules DSL


[ 298 ]

grant {
extend 1
}
}
}

onPurchase = {
reward ( "Earn 10% bonus points on all games." ) {
condition {
isGame
}
grant {
points media.points / 10
}
}
}

onUpgrade = {
reward ("Upgrade to PLUS and get 100 free points") {
condition {
toPlan == "PLUS"
}
grant {
points 100
}
}
}

The RewardService class

We now have a very usable DSL design that can express the rewards as a script.
All that remains is to implement the means to integrate this DSL into our application.
It makes sense to package all of this functionality into a service class that can
be called by our application when needed. To do this, we provide a class called
RewardService.


The RewardService class provides a static method, loadRewardRules, that needs
to be called first, in order to initialize the rewards. This method takes care of the
initial loading of the rewards from the script file. Initial default implementations
of the onConsume, onPurchase, and onUpgrade closures are provided by the
RewardService class. Their only purpose is to provide a stub, which will be
called if any of these closures has not been provided by the DSL. Once loaded, the
RewardService class maintains static copies of the closure, to be called as needed by
the event hook methods.


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