Search

Dark theme | Light theme

June 14, 2016

Ratpacked: Include Files In The Ratpack Groovy DSL

When we define our Ratpack application using the Groovy DSL in a file ratpack.groovy, we can split up the definition in multiple files. With the include method inside the ratpack configuration closure we can use the file name of the file we want to include. The file that we include also contains a ratpack configuration closure. We can use the same bindings, handlers and serverConfig sections. The bindings configuration is appended to the parent configuration. The handlers and serverConfig configuration is merged with the parent configuration.

In an example project we have the following ratpack.groovy, that includes two extra files: course.groovy and loghandler.groovy:

// File: src/ratpack/ratpack.groovy
import java.nio.file.Paths

import static ratpack.groovy.Groovy.ratpack

ratpack {
    bindings {
        bindInstance(new Integer(42))
    }

    handlers {
        get { Integer answer ->
            render "The answer is $answer"
        }
    }

    // File name of external file to include.
    include 'course.groovy'
    
    // Argument of the include method can
    // also be a Path.
    include Paths.get('loghandler.groovy')
}

In the course.groovy file we add a CourseService type to the registry and use it in a handler:

// File: src/ratpack/course.groovy
import mrhaki.ratpack.course.CourseService
import mrhaki.ratpack.course.impl.CourseMemoryStore

import static ratpack.groovy.Groovy.ratpack
import static ratpack.jackson.Jackson.json

ratpack {
    bindings {
        bind(CourseService, CourseMemoryStore)
    }
    
    handlers {
        get('course/:courseId') { CourseService courseService ->
            final String id = pathTokens.courseId
            
            courseService
                    .getCourse(id)
                    .then { course -> render(json(course))}
        }
    }
}

We also add a RequestLogger handler in the loghandler.groovy file:

// File: src/ratpack/course.groovy
import ratpack.handling.RequestLogger

import static ratpack.groovy.Groovy.ratpack

ratpack {
    handlers {
        all(RequestLogger.ncsa())
    }
}

Written with Ratpack 1.3.3.