Creating a Groovy ConfigObject from a Closure

The Groovy ConfigObject and ConfigSlurper are very nice for replacing properties and XML configuration files with Groovy. Surprisingly though, there’s no obvious way to get a ConfigObject directly from a closure. The interface requires either the URL or filename of a script file, or a Script object.

Fortunately, there’s an easy way wrap a closure to make it work like a Script:

class ClosureScript extends Script {
    Closure closure
    def run() {
        closure.resolveStrategy = Closure.DELEGATE_FIRST
        closure.delegate = this
        closure.call()
    }
}

This makes it trivial to include a configuration configuration directly inside a script and treat it just like an external script.

def config = {
  environments {
    development {
      host = 'localhost'
      port = 8080
    }
  }
}
def env = 'development'
def settings = new ConfigSlurper(env).
    parse(new ClosureScript(closure: config))
println "host is $settings.host, port is $settings.port"

Leave a Reply