Search code examples
groovyratpack

How to use ConfigData in ratpack.groovy?


I am trying to follow along with the example Ratpacked: Using PostgreSQL Database but I get the error 'of' in 'ratpack.config.ConfigData' can not be applied to '(groovy.lang.Closure<ratpack.config.ConfigDataBuilder>)' in IntelliJ IDEA.

ratpack {
    bindings {
        // Create generic configuration.
        final ConfigData configData = ConfigData.of { ConfigDataBuilder builder ->
            // Set configuration properties.
            // We can use the yaml, json and other
            // ConfigDataBuilder methods to read
            // configuration from other sources.
            builder.props(
                    ['postgres.user'        : 'postgres',
                     'postgres.password'    : 'secret',
                     'postgres.portNumber'  : 5432,
                     'postgres.databaseName': 'postgres',
                     'postgres.serverName'  : '192.168.99.100'])
            builder.build()
        }

        // Create instance of PostgresConfig 
        // that is used for the 
        // configurable module PostgresModule.
        bindInstance PostgresConfig, configData.get('/postgres', PostgresConfig)
        // Initialise module to create DataSource.
        module PostgresModule

        // Initialize SqlModule to provide
        // Groovy SQL support in our application.
        module SqlModule
    }
}

Solution

  • IntelliJ shows an inspection warning about incompatible assignments. The code is valid and when you run the application it just works fine. If the inspection is shown as an error you might want to lower the reporting level for these assignments. Otherwise you would need to cast the closure to Action<ConfigDataBuilder> to make IntelliJ happy, but it also clutters the ratpack.groovy. The code with proper casting is then:

    ...
            // Create generic configuration.
            final ConfigData configData = ConfigData.of({ ConfigDataBuilder builder ->
                // Set configuration properties.
                // We can use the yaml, json and other
                // ConfigDataBuilder methods to read
                // configuration from other sources.
                builder.props(
                        ['postgres.user'        : 'postgres',
                         'postgres.password'    : 'secret',
                         'postgres.portNumber'  : 5432,
                         'postgres.databaseName': 'postgres',
                         'postgres.serverName'  : '192.168.99.100'] as Map<String, String>)
                builder.build()
            } as Action<ConfigDataBuilder>)
    ...