2016-04-29 67 views
2

我有一組像這樣的任務:如何重構來自類似任務的重複代碼?

// task to run the groovy script 
task('Ls', type: JavaExec) { 

    environment 'gateway', props.gateway 
    environment 'username', props.username 
    environment 'password', props.password 

    main = 'Ls' 
    classpath = sourceSets.main.runtimeClasspath 
} 
task('Mkdir', type: JavaExec) { 

    environment 'gateway', props.gateway 
    environment 'username', props.username 
    environment 'password', props.password 

    main = 'Mkdir' 
    classpath = sourceSets.main.runtimeClasspath 
} 

task('Put', type: JavaExec) { 

    environment 'gateway', props.gateway 
    environment 'username', props.username 
    environment 'password', props.password 

    main = 'Put' 
    classpath = sourceSets.main.runtimeClasspath 
} 

task('Example') { 
    dependsOn Ls, Mkdir, Put 
} 

有沒有辦法,我可以重構環境設置塊,這樣,我沒有那麼多的重複代碼的方法嗎?

回答

3

肯定的:

['Ls', 'Mkdir', 'Put'].each { taskName -> 
    task "$taskName"(type: JavaExec) { 

     environment 'gateway', props.gateway 
     environment 'username', props.username 
     environment 'password', props.password 

     main = taskName 
     classpath = sourceSets.main.runtimeClasspath 
    } 
}