Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Example DSL – GeeTwitter


[ 132 ]

We can now try out our DSL from the command line. To run a script to search for
tweets about the Groovy and Grails eXchange event, we can save the following in a
file called ggx.gtwit and invoke the GTweet_1.0 shell script:


import static GeeTwitter.*

search "Groovy Grails eXchange"

Adding built-in methods


However simple our DSL might now look, the need to preface our method calls with
GeeTwitter is one final piece of boilerplate code that it would be nice to remove. In
some of the previous examples we have used a static import to do this, but it is still
not very intuitive to a non Java/Groovy programmer why we are doing this. Since
we are evaluating the DSL script ourselves, rather than allowing Groovy to do it,
we still have some scope to do this.


It would certainly be nicer to be able to write:


eachFollower {
sendMessage it, "Thanks for taking the time to follow me!"
}

This assumes that the eachFollower method is built in to the DSL, rather than the
more verbose:


GeeTwitter.eachFollower {
GeeTwitter.sendMessage (it,
"Thanks for taking the time to follow me!")
}

Groovy provides two mechanisms that allow us achieve just this. Later in the book,
we will look at how we can manipulate the binding to achieve this. For this chapter,
we will look at a more straightforward mechanism, which exploits the compilation
model for Groovy scripts.


Whenever we run a Groovy script, the script gets compiled behind the scenes into a
class derived from the Groovy Script class (see http://docs.groovy-lang.org/
latest/html/gapi/groovy/lang/Script.html). Most of the time, we are unaware
of the fact that Script has just a few methods of interest to us. For instance, to access
the binding of a script, we reference the binding property. When we do so, what we
are in fact doing is calling the Script.getBinding() method. Similarly, when we
used evaluate in the previous section to load and run our DSL from the launcher
script, we were actually calling the Script.evaluate() method.


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