Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 6

[ 133 ]

Instead of calling Script.evaluate() in the launch script, we can use
the GroovyScript class to do the same thing. However, now we have the
option of initializing the GroovyScript object that evaluates our DSL with a
CompilationConfiguration object (See http://docs.groovy-lang.org/latest/
html/gapi/org/codehaus/groovy/control/CompilerConfiguration.html).
This now gives us control over how the compilation of the script will be handled.


CompilationConfiguration gives us the ability to set a number of compilation
attributes, including the classpath to be used and the PrintWriter object to be used
as a standard output. We can even add the static import for the GeeTwitter class.
The command-line script needs to be modified as follows:


#!/usr/bin/env groovy
import org.codehaus.groovy.control.*
import org.codehaus.groovy.control.customizers.*

if(args) {
def conf = new CompilerConfiguration()
def imports = new ImportCustomizer()
imports.addStaticStar("GeeTwitter")
conf.addCompilationCustomizers(imports)
def shell = new GroovyShell(this.class.classLoader,
new Binding(), conf)
shell.evaluate (new File(args[0]))
} else
println "Usage: GTweet_2.0 <script>"

The CompilationConfiguration class also provides a method
CompilationConfiguration.setScriptBaseClass(), which allows us to provide
an alternative subclass of Script to be used for the base class of our script instance:


abstract class MyBaseScript extends Script {
def builtIn ( a ) { println a }
}

If we provide the preceding MyBaseScript class as the alternate Script class, any
script that we evaluate by using this class will have the builtIn method available by
default. There is nothing magical here; it's now just a method of the Script class that
gets compiled into our environment. We can now rewrite our GeeTwitter class to
make it a subclass of Script. Let's call it GeeTwitterScript, in order to distinguish
it from the original:


@Grab(group='org.twitter4j', module='twitter4j-core',
version='[4.0,)')
import twitter4j.*
Free download pdf