Including a groovy script in another groovy
Another way to do this is to define the functions in a groovy class and parse and add the file to the classpath at runtime:
File sourceFile = new File("path_to_file.groovy");
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
GroovyObject myObject = (GroovyObject) groovyClass.newInstance();
As of Groovy 2.2 it is possible to declare a base script class with the new @BaseScript
AST transform annotation.
Example:
file MainScript.groovy:
abstract class MainScript extends Script {
def meaningOfLife = 42
}
file test.groovy:
import groovy.transform.BaseScript
@BaseScript MainScript mainScript
println "$meaningOfLife" //works as expected
evaluate(new File("../tools/Tools.groovy"))
Put that at the top of your script. That will bring in the contents of a groovy file (just replace the file name between the double quotes with your groovy script).
I do this with a class surprisingly called "Tools.groovy".