Implementing a Rules DSL
[ 292 ]
if (binding.useAnd)
binding.result = (closure() && binding.result)
else
binding.result = (closure() || binding.result)
}
To implement the allOf closure block, we store the current states of result and
useAnd, before calling the child closure. We && or || the stored result with the new
result from the closure, giving us the new boolean state of the expression. The
starting presumption of an allOf block is that it is true. It will be set to false
if any one of the child conditions returns false.
binding.allOf = { closure ->
closure.delegate = delegate
def storeResult = binding.result
def storeAnd = binding.and
binding.result = true // Starting premise is true
binding.and = true
closure()
if (storeAnd) {
binding.result = (storeResult && binding.result)
} else {
binding.result = (storeResult || binding.result)
}
binding.and = storeAnd
}
The anyOf closure block is identical to allOf except that the starting presumption is
false. The operator that we now use is ||, so if any one of the child conditions returns
true, the overall result will be true.
binding.anyOf = { closure ->
closure.delegate = delegate
def storeResult = binding.result
def storeAnd = binding.and
binding.result = false // Starting premise is false
binding.and = false
closure()
if (storeAnd) {
binding.result = (storeResult && binding.result)
} else {
http://www.ebook3000.com