Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of this keyword as an argument to the class constructor in Jenkins file

I recently came across the following lines in Jenkinsfile

def obj = new Foo(this, params)
obj.someMethod()

what is the use of this keyword as an argument to the class constructor?

like image 580
k_vishwanath Avatar asked Nov 08 '22 09:11

k_vishwanath


1 Answers

this keyword is used to pass pipeline steps to a library class, in a constructor, or just one method

Suppose I have the following pipeline

pipeline{
  agent any
  stages {
    stage {
      steps {
        echo "Inside Steps block"
        script {
           echo "Hello World"
           sh 'date'
           def obj = new Bar(this)
           obj.test()
        }
      }
    }
  }
}

And this is how the class file looks

class Bar implements Serializable {
  def steps
  Bar(steps) {
    this.steps = steps
  }

  void test() {
    this.steps.echo 'Hello World inside class Method'
    this.steps.sh 'date'
  }
}

So basically whatever steps you can execute inside pipeline can be used inside the groovy class by passing this keyword to the class constructor

More info can be found from the official doc

like image 59
k_vishwanath Avatar answered Nov 14 '22 23:11

k_vishwanath