如何在Groovy中设置闭包属性,就像在Gradle中一样?

时间:2016-06-13 09:00:30

标签: gradle groovy

以下是Gradle documentation,我不明白:

idea {

  //if you want parts of paths in resulting files (*.iml, etc.) to be replaced by variables (Files)
  pathVariables GRADLE_HOME: file('~/cool-software/gradle')

  module {
    //if for some reason you want to add an extra sourceDirs
    sourceDirs += file('some-extra-source-folder')

设置idea.module.sourceDirs值。

如何在没有Gradle的纯Groovy中实现它?我想知道它潜在的机制。

2 个答案:

答案 0 :(得分:1)

感谢@Steinar,我使用以下代码修复:

def file(String p) {
    new File(p)
}

class Idea {
    class Module {
        Set<File> excludeDirs = []
    }

    void module(Closure c) {
        c.delegate = new Module()
        c()
    }
}

void idea(Closure c) {
    c.delegate = new Idea()
    c()
}

idea {
    module {
        excludeDirs += file("smth")
    }
}

答案 1 :(得分:0)

根据您提出的解决方案@asullaherc,您无法在调用idea { moduleidea.module { ...之间做出选择,因此我宁愿选择其他解决方案。

这是您要为案例创建的所有闭包的基类:

class SectionBase extends Closure<Object> {
    SectionClosure() {
        super(null)
    }
    Object doCall(final Closure inner) {
        inner.delegate = this
        inner()
    }
}

这将是一个实现(&#34; Gradle风格&#34;):

class DependenciesSection extends SectionBase {
    void compile(packageName) {
        println "compile: $packageName"
    }
    void testCompile(packageName) {
        println "testCompile: $packageName"
    }
}

现在我们创建一个实例:

def dependencies = new DependenciesSection()

稍微乱用一下:

// You can do it either this way...
dependencies {
    compile 'com.my.package1'
    compile 'com.my.package2'
    testCompile 'com.my.package3'
}

// ...or also the other
dependencies.compile 'com.my.package4'
dependencies.testCompile 'com.my.package5'

输出结果为:

compile: com.my.package1
compile: com.my.package2
testCompile: com.my.package3
compile: com.my.package4
testCompile: com.my.package5