Gradle Goodness: Using Objects for Version
One of the great things of Gradle is that the build scripts are code. We can use all the features of the Groovy language, we can refactor our build scripts to make them more maintainable, we can use variables and properties to define values and much more, just like our application code. In this post we see how we can create a class to define a version in our build script. To set the version of a Gradle project we only have to assign a value to the version property. Normally we use a String value, but we can also assign an object. Gradle will use the toString() method of the object to get the String value for a version. In the following build script we define a new class Version in our build script. We create an instance of the class and assign it to the version property. With the task printVersion we can see the value of the version property:
version = new Version(major: 2, minor: 1, revision: 14)
task printVersion {
doFirst {
println "Project version is $version"
}
}
defaultTasks 'printVersion'
class Version {
int major, minor, revision
String toString() {
"$major.$minor.$revision"
}
}