Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 11

[ 297 ]

We implement the extend action through a method call on the BroadbandPlus
service. The points action is just a shorthand way of updating the account points
value that is always in the binding. In this way, we can extend the vocabulary of the
DSL to include any actions that we might like to perform on the system.


We further improve the legibility of our scripts by adding some shorthand to be used
in conditionals. Common tests that we encounter when deciding to grant a reward
are the type of media being consumed or purchased, and whether it is a new release
or not. We add some shorthand to the DSL by including boolean binding variables
for these common conditions.


binding.is_new_release = media.newRelease
binding.is_video = (media.type == "VIDEO")

The offers

Putting all of these DSL features together, we now have a mini DSL that will allow us
to define how rewards should be granted to subscribers based on their consumption
and purchasing behavior. Earlier in the chapter, we listed some reward types that
we would like to support. Let's see now how well we can express those rewards by
using the DSL that we have just designed. If we've done our job well, the reward
DSL should be all we need to read to fully understand the intent and impact of
applying the reward.


onConsume = {
reward ( "Watch a Pixar Movie, get 25% extra points." ) {
allOf {
condition {
media.publisher == "Disney"
}
condition {
isVideo
}
}

grant {
points media.points / 4
}
}
reward ( "Rent a new release, get extra night rental" ) {
condition {
isNewRelease
}
Free download pdf