Implementing a Rules DSL
[ 286 ]
We know that closures and methods in Groovy will return a value even when no
return statement is used. The value returned is the result of the last statement
executed in the method or closure. We can exploit this in our DSLs. The value
returned from innerBlock in the preceding code is the result of message = "Hello,
World!"βin other words, the string "Hello, World!". We can define a closure that
captures a string value from the DSL, as follows:
binding.messageBlock = { closure ->
closure.delegate = delegate
binding.message = closure()
println "messageBlock: ${binding.message}"
}
This allows us to define a message string by using the following DSL code:
outerBlock {
messageBlock {
"Hello, World!... message"
}
}
Using this style, we can define a DSL block that expects a Boolean return value and
use it to define a conditional expression. Going back to the reward DSL we used
earlier, we could write the following conditional DSL code:
reward {
appliesWhen {
ACTIVE && REWARD_THRESHOLD_EXCEEDED
}
}
We can document to our DSL users that appliesWhen declares a condition that must
be met if the reward between the curly braces is to be awarded.
Building a rewards DSL
The old adage that 80 percent of business comes from your existing customers
while 20 percent comes from new customers is as true today as it ever was. Every
business, at some point in time, considers offering incentives to its customers in
order to increase sales. Rewards can take the form of everything from the selective
discounting of end-of-line items, through buy-one-get-one-free promotions, to
customer loyalty points schemes.
http://www.ebook3000.com