Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including a groovy script in another groovy

Tags:

groovy

I have read how to simply import a groovy file in another groovy script

I want to define common functions in one groovy file and call those functions from other groovy files.

I understand this would be using Groovy like a scripting language i.e, I dont need classes/objects. I am trying to something like dsl that can be done in groovy. All variables will be asserted from Java and I want to execute groovy script in a shell.

Is this possible at all ? Can someone provide some example.

like image 846
Kannan Ekanath Avatar asked Feb 03 '12 22:02

Kannan Ekanath


People also ask

How you can include a Groovy script in another Groovy?

For example, using "some/subpackage/Util. groovy" would result in searching at WORK_DIR/some/subpackage/Util. groovy . Follow the Java class naming convention to name your groovy scripts.

What is import file include in Groovy?

A simple import is an import statement where you fully define the class name along with the package. For example the import statement import groovy. xml. MarkupBuilder in the code below is a simple import which directly refers to a class inside a package.


2 Answers

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".

like image 129
jmq Avatar answered Oct 07 '22 02:10

jmq


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 
like image 42
emesx Avatar answered Oct 07 '22 02:10

emesx