Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Implementing a Rules DSL


[ 302 ]

GroovyShell shell = new GroovyShell(binding)
shell.evaluate("on_purchase.delegate =
this;onPurchase()")
}
}
void applyRewardsOnUpgrade(account, plan) {
if (on_upgrade_provided) {
Binding binding = new Binding()
binding.account = account
binding.to_plan = plan
binding.from_plan = account.plan
prepareClosures(binding)

GroovyShell shell = new GroovyShell(binding)
shell.evaluate("on_upgrade.delegate = this;onUpgrade()")
}
}
}

The BroadbandPlus application classes

In order to show this DSL working, we need to flesh out some classes in order to
implement a rudimentary application skeleton for our imaginary BroadbandPlus
service. We won't scrutinize these classes in too much detail, as their main purpose is
to provide the hooks to exercise our DSL, and not to represent a working system.


To begin with, we need to define an Account class. The Account class maintains
the basic subscription details for a subscriber, including the plan he is on and his
remaining points for this period. It also maintains the current list of media that he
has access to. Once the consumption of an item starts, the media is added to this list,
along with an expiry date. The expiry date can be extended at any time by calling the
extendMedia method.


class Account {
String subscriber
String plan
int points
double spend
Map mediaList = [:]
void addMedia (media, expiry) {
mediaList[media] = expiry
}
void extendMedia(media, length) {
mediaList[media] += length
}

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