我正在尝试将使用 Jenkins Job DSL 插件的代码分解为可重用的部分,我怀疑我的问题是 Groovy 通用的,而不是 Jenkins 特有的。例如,我想重用这个块的一部分:
freeStyleJob() {
//generic stuff
name "something"
description "something else"
//custom stuff
scm {
svn {
//etc....
}
}
}
通过将名称和描述放在实用方法中(显然我想做的不仅仅是在现实生活中)。但是,我找不到为当前范围创建闭包的正确语法。这是我认为它应该看起来的样子:
def jobCommonItems() {
return {
//generic stuff
name "something"
description "something else"
}
}
freeStyleJob() {
jobCommonItems().call()
//custom stuff
scm {
svn {
//etc....
}
}
}
(也许有一个closure.delegate = this 某处)
但是,这不适用于关闭。它适用于方法,如下所示:https ://dzone.com/articles/groovy-closures-owner-delegate
为了说明,这里有一个测试显示了三种可能的语法组合:
String myString = "Top Level: string"
def myMethod() {
println "Top Level: Method"
}
def myClosure = { println "Top Level: Class"}
class MyClass1 {
String myString = "Class1: String"
def myMethod() {
println "Class1: Method"
}
def myClosure = { println "Class1: Closure"}
}
class MyClass2 {
String myString = "Class2: String"
def myMethod() {
println "Class2: Method"
}
def myClosure = { println "Class2: Closure"}
}
class MyClass {
def closure = {
println "In-Class generated closure begins, delegate is ${delegate}"
myMethod()
myClosure()
println myString
}
}
def closure = new MyClass().closure
closure.delegate = new MyClass1()
closure()
closure = new MyClass().closure
closure.delegate = new MyClass2()
closure()
// This fails - it can find the top level method, but not closure or string
closure.delegate = this
closure()
def methodMissing(String methodName, args) {
println "Method not found in class ${this} by name ${methodName}"
}
我收到一个错误,即闭包不在主类中(即测试 test.groovy):在类 test@60611244 中找不到方法,名称为 myClosure
我尝试将委托更改为“this”,尝试更改查找策略等。我可能缺少一些基本的东西。