I'm trying to learn how to create a global closure in groovy (like the println closure). I have the following code:
a.groovy
def header = Tools.&header
header 'groovy script a'
b.groovy
def header = Tools.&header
header 'groovy script b'
tools.groovy
class Tools {
def static header(String str) {
println("\n${str}")
println("-" * 80)
}
}
I would like to avoid:
def header = Tools.&header
in every groovy script where I would like to use the Tools.header() (and just use header closure when I import the tools package). I tried to put the definition after the Tools class, but that did not work. Can this be done? Is there a better way to handle this?
EDIT: (using a metaClass and the evaluate method unless there is a simpler way to include an external script):
a.groovy
evaluate(new File("Tools.groovy"))
header 'groovy script a'
b.groovy
evaluate(new File("Tools.groovy"))
header 'groovy script b'
tools.groovy
Object.metaClass.header = {str ->
println("\n${str}")
println("-" * 80)
}