Ratpacked: Type Conversion For Path Tokens

In Ratpack we can use path token as variable parts of a request. We can access a path token via the PathBinding instance that is added to the context registry by Ratpack. There is a shorthand method getPathTokens to get the PathTokens object. To get the value for a token we use the get method or with the Groovy DSL we can use square brackets with the name of the token. If we expect a token value to be of a certain type, like a Long
or Boolean, we can use the asLong or asBoolean method. The value is then converted to the correct type and if the conversion fails an exception is thrown. The exception will be converted to a 500 status code in the response by the default error handler.

The PathTokens class has methods for converting to Long, Byte, Integer, Short and Boolean types with the methods asLong, asByte, asInteger, asShort and asBoolean

In the following sample Ratpack application we use a path token with the name id. We use the asLong method to convert it to a Long instance:

With the following specification we can see that a valid value is converted correctly and an invalid value gives a 500 error response code:

Written with Ratpack 1.1.1.

Original article

This entry was posted in Ratpack and tagged , by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *