build.gradle文件中的groovy - 如何交换闭包/方法

时间:2015-07-09 21:54:55

标签: groovy android-gradle build.gradle

寻找一位时髦的专家来帮助我。在我的android build.gradle文件中,我有

以下定义:

 apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply from: 'other.gradle'//this contains another flavor


//A method to detect if another gradle build file is available
def boolean isOtherBuildFile() {
     return new File('other.gradle').exists()
    }


    android {
        compileSdkVersion 21
        buildToolsVersion "21.1.1"

        defaultConfig {
            //blah blah not important
        }

        buildTypes {
            debug {
                //blah blah not important
            }

            release {
              //blah blah not important

            }
        }

            productFlavors {
                def STRING = "String"
                def BOOLEAN = "boolean"
//i'd like to be able to swap out this mock closure below with another one
                mock {
                    applicationId "org.example.mock"
                    versionName = "1.5" + '-mock'
                    buildConfigField STRING, GCM_SENDER_ID, '"123456789"'
                    buildConfigField STRING, BASE_ENDPOINT, '"localhost/"'
                }
              }

在名为other.gradle的文件中,我想将mock重新定义为其他内容。例如在other.gradle中,我可以像这样定义模拟:

 mock {
           applicationId "com.tutorial.mock"
           versionName = "2.4" + '-mock'
           buildConfigField STRING, GCM_SENDER_ID, '"987654321"'
           buildConfigField STRING, BASE_ENDPOINT, '"www.mymockdomain.com/"'
            }

所以这就是我想要完成的事情:我想检查一下puesdo代码,如下:

if(isOtherBuildFile())
then
    //use the mock defined in other.gradle

else 
   //continue to use the mock defined in build.gradle

它是在Android工作室,但我不认为它是android与groovy语法有任何关系,我希望。我也可以更换整个风味封闭,因为这是一个更好的解决方案。

1 个答案:

答案 0 :(得分:0)

应该足够了:

if(isOtherBuildFile() {
   project.apply: 'other.gradle'
} else {
   mock {}
}

你有没试过?