Groovy: how to call closure in top scope from another closure

时间秒杀一切 提交于 2019-12-06 12:42:35

The job factory methods like freeStyleJob return an object that can be used to apply more configuration using the with method. That method expects a closure argument which has the same properties as the closure passed to the freeStyleJob method.

def basicConfiguration() {
    return {
        description('foo')
        scm {
            // whatever
        }
    }
}

def myJob = freeStyleJob('example') {
    publishers {
        // more config
    }
}
myJob.with basicConfiguration()

The script itself is an instance of DslFactory which is the interface containing e.g. the freeStyleJob method. You can pass that object to classes or methods to use the freeStyleJob.

def myJobFactory(def dslFactory, def jobName) {
    dslFactory.freeStyleJob(jobName) {
        description('foo')
    }
}

def myJob = myJobFactory(this, 'example')

And then you can use the myJob object to apply further configuration using with.

How about something like this?

def jobCommonItems(job) {
    job.name = "something"
    job.description = "something else"
}

freeStyleJob() {
    jobCommonItems(this)

    //custom stuff
    scm {
       svn {
           //etc....
       }
    }
}

Seems that one solution is to invert the relationship like this, and to pass "this" as the context to find DSL top-level closures.

class Utils {
    static def makeMeABasicJob(def context) {
        context.freeStyleJob() {
            //generic stuff
            name "something"
            description "something else"
        }

    }
}

def job1 = Utils.makeMeABasicJob(this) //Passing the groovy file class as the resolution context
job1.with({
    //custom stuff
    scm {
        svn {
            //etc....
        }
    }
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!