Implementing a Rules DSL
[ 296 ]
In the preceding snippet, the evaluate method of the DSL script will set saved to be
the closure that is provided within the script. We can store this in a closure variable
to be reused later. Evaluating the saved closure in GroovyShell once again gives us
the opportunity to set up the binding to support our DSL. Prior to calling saved() in
the evaluated script, we need to set its delegate. This ensures that the saved closure
inherits the binding that we pass into the script.
def binding = new Binding()
binding.saved = store_saved
binding.deferred = { closure ->
closure.delegate = delegate
closure()
}
def shell = new GroovyShell(binding)
shell.evaluate("saved.delegate = this; saved()")
We now have a means of stripping out the closures defined within the main script
and executing them at will.
Convenience methods and shorthand
The final piece of our DSL that we need to take care of is to add some convenience
methods and shorthand binding variables, in order to make the DSL more legible.
First, we add some actions to be taken when a reward is granted. In the case of our
rewards DSL, the actions that we want for now are the ability to extend access to a
video or game, or to add points to a subscriber's account.
In reality, we would implement many more of these, including granting access to
specific videos or games. The features that we can add to the DSL are limited only
by our imagination and the features provided in the backend systems that we are
working with. Most likely our DSL would evolve over time, with new action verbs
and other shorthand features being added.
binding.extend = { days ->
def bbPlus = new BroadbandPlus()
bbPlus.extend( binding.account, binding.media, days)
}
binding.points = { points ->
binding.account.points += points
}
http://www.ebook3000.com