29

I have the following JobDSL spec:

job {
  steps {
    gradle('generateLock saveLock', '-PdependencyLock.includeTransitives=true', true) { node ->
      node / wrapperScript('${NEBULA_HOME}/gradlew')
    }
    gradle('check', '', true) { node ->
      node / wrapperScript('${NEBULA_HOME}/gradlew')
    }
  }
}

I'd like to refactor the common code, say, into a function:

def gradlew(String tasks, String options) {
  gradle(tasks, options, true) { node ->
    node / wrapperScript('${NEBULA_HOME}/gradlew')
  }
}

But the gradle function isn't visible from within the gradlew function. What's the right way to do this?

Noel Yap
  • 18,822
  • 21
  • 92
  • 144

1 Answers1

41

The curly brackets form a Groovy closure. Each closure has a delegate object to which method calls are directed. And the delegate can be accessed via the delegate property. You can pass that delegate to the helper function to get access to it's methods.

def gradlew(def context, String tasks, String options = '') {
  context.gradle(tasks, options, true) { node ->
    node / wrapperScript('${NEBULA_HOME}/gradlew')
  }
}
job {
  steps {
    gradlew(delegate, 'generateLock saveLock', '-PdependencyLock.includeTransitives=true')
    gradlew(delegate, 'check')
  }
}
David Resnick
  • 4,891
  • 5
  • 38
  • 42
daspilker
  • 8,154
  • 1
  • 35
  • 49
  • 5
    I would recommend doing some explicit examples on the project wiki on how to extract commonly used code. We were searching for the same thing for quite some time. – Matthias B Dec 01 '15 at 10:33
  • 3
    I'm going to update the Job DSL wiki page about configure blocks, see https://github.com/jenkinsci/job-dsl-plugin/pull/683 – daspilker Dec 01 '15 at 12:34
  • What does the forward slash do after node -> node / ... ? – niken Aug 16 '16 at 19:59
  • 2
    @daspilker it took me about 3 hours of searching to finally stumble across this answer and realize that i needed the delegate property. I had been using "this". Thanks so much for the help!! – Allen Rice Dec 20 '16 at 23:29
  • I'd now like to refactor a lot of commmon code into a helper class. But 'Process Job DSLs' finds my helper class alongside my JobDSL class and tries to run it as a JobDSL. How to overcome this? – Ed Randall Oct 13 '17 at 14:47