Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Ratpacked: Include Files in the Ratpack Groovy DSL

DZone's Guide to

Ratpacked: Include Files in the Ratpack Groovy DSL

Ratpack Groovy files don't have to get all oversized and hard to manage; they can be broken up.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
ratpack ,groovy

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}