PageRenderTime 20ms CodeModel.GetById 14ms app.highlight 3ms RepoModel.GetById 2ms app.codeStats 0ms

/R/route.r

http://github.com/hadley/sinartra
R | 51 lines | 27 code | 7 blank | 17 comment | 3 complexity | 9d1d4b4e55545a38793b8a17e393b8c2 MD5 | raw file
 1#' Parse route (with parameters) into regular expression.  
 2#'
 3#' @param route route url.
 4#' @return 
 5#'   \item{match}{regular expression to match route}
 6#'   \item{params}{parameter names}
 7route_re <- function(route) {
 8  # Escape special characters that can occur in both urls and regexps
 9  route <- stringr::str_replace_all(route, "([.])", "\\\\\\1")
10  
11  # Extract parameters
12  params <- stringr::str_extract_all(route, ":[a-zA-Z0-9_.]+|[*]")[[1]]
13  
14  keys <- stringr::str_replace_all(params, ":", "")
15  keys[keys == "*"] <- "splat"
16  
17  match <- stringr::str_c("^", route, "$")
18  match <- stringr::str_replace_all(match, ":[a-zA-Z0-9_.]+", "([^/?&#]+)")
19  match <- stringr::str_replace_all(match, "[*]", "(.*?)")
20  
21  list(
22    match = stringr::str_c(match, collapse = "/"),
23    params = keys
24  )
25}
26
27#' Generate functions to match specified route.
28#'
29#' @param route route url
30#' @return 
31#'   \item{match}{function returning \code{TRUE} if argument matches route,
32#'     \code{FALSE} otherwise}
33#'   \item{params}{function that parses path and returns named list of
34#'      parameters}
35route_matcher <- function(route) {
36  re <- route_re(route)
37  
38  list(
39    match = function(path) stringr::str_detect(path, re$match),
40    params = function(path) {
41      matches <- stringr::str_match(path, re$match)[1, -1]
42      if (length(re$params) > 0) {
43        # c is simplest way convert from array to vector
44        c(tapply(matches, re$params, "c", simplify = FALSE))
45      } else {
46        list()
47      }
48    }
49  )
50}
51