Monday, March 28, 2011

Grails Goodness: Access Configuration in Grails Scripts

We can create our own scripts in Grails that can be executed from the command-line. To access values from the properties we have defined in grails-app/conf/Config.groovy we must start with adding the following line to the top of our script:

includeTargets << grailsScript('_GrailsPackage')

With this include we get access to the checkConfig task.

Next we must execute this task after the compile task to get a config variable in our script. The script variable config contains the values of our configuration defined in the Grails configuration files.

The following script contains some sample configuration properties for different environments.

// File: grails-app/conf/Config.groovy

blog.sample = 'Blog sample'
environments {
    development {
        blog.sample = 'Value for development'


Let's create a new script Sample.groovy with the following command: $ grails create-script sample. We open the file and add:

// File: scripts/Sample.groovy
includeTargets << grailsScript('_GrailsPackage')

target('sample': 'Show usage of configuration information in Grails scripts.') {
    depends(compile, createConfig)

    println 'Sample = ' + config.blog.sample

setDefaultTarget 'sample'

If we execute our task with $ grails sample we get the following output:

Sample = Value for development

And if we run $ grails test sample we get:

Sample = Blog Sample

The original source for this information is Grails mailing list.