Thursday, August 19, 2010

Grails UrlMappings - mutually exclusive patterns

Let's say, I have URL patterns that are mutually exclusive and have to map to 2 different controllers. For instance, if I have an enum Vals with the following values: ROCK, PAPER, SCISSORS, and I want URLs like

/root/group/rock (or ROCK)
/root/group/paper (or PAPER) 
/root/group/scissors (or SCISSORS) to map to YouWinController

and

/root/group/(everything-else-but-ROCK|rock|PAPER|paper|SCISSORS|scissors) to map to YouLoseController


Both URL patterns are very similar, because each one consists of 3 strings separated by '/'. We can start by defining some constraints, but at the same time we have to define the exclusive pattern first. In this case, exclusive pattern is the one mapping to YouLoseController.

class UrlMappings {
    static mappings = {
        "/root/group/$loseParam"(controller: "youLose", action: "/loseAction")
        "/root/group/$winParam"(controller: "youWin", action: "/winAction") {
            constraints {
                  // get all string values from the enum
                  def list = stringList(Vals) 
                  // make sure lowercase values are also included
                  list.addAll(list*.toLowerCase()) 
                  $winParam(inList: list)
            }
        }
    }
}

No comments:

Post a Comment