Alternate Syntax For URL Mapping In Grails Saturday, May 19, 2007

One of the cool new features that was introduced with Grails 0.5 is Custom URL Mapping. The syntax for declaring the mapping looks something like this...


class MyUrlMappings {
static mappings = {
"/product/$id" {
controller = "product"
action = "show"
}

"/$blog/$year/$month/$id" {
controller = "blog"
action = "show"
constraints {
year(matches:/\d{4}/)
month(matches:/\d{2}/)
}
}
}
}

Since the release we have added support for an alternate syntax (which I happen to like) that looks like this...

class MyUrlMappings {
static mappings = {
"/product/$id" (controller:"product", action:"show")

"/$blog/$year/$month/$id" (controller:"blog", action:"show"){
constraints {
year(matches:/\d{4}/)
month(matches:/\d{2}/)
}
}
}
}

Dynamic languages like Groovy make these sorts of things really easy to support. Behind the scenes of this url mapping there there is no grammar file and no tangly parser to manage. The configuration file is plain old groovy code. Blurring the line between code and configuration files by using a DSL like this is so much easier in Groovy that it might be in a language like C++ or Java. You have got to love it. :)

1 comments:

theguildedpage said...

Wow, there is so much effective info above!