Advertisement
Guest User

Untitled

a guest
Oct 10th, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ;; note- path-pattern should escape any regex patterns first, but doesn't.
  2.  
  3. (defn index-map [path-pattern]
  4.   "Takes a path \"/foo/:bar/:what\" and returns the indices into the regex #\"/foo/([^/]*)/([^/]*)\""
  5.   (zipmap (iterate inc 1)
  6.           (map (comp keyword clojure.string/join rest)
  7.                (filter #(re-matches #"^:.*" %)
  8.                        (clojure.string/split path-pattern #"/")))))
  9.  
  10. (defn to-regex [path-pattern]
  11.   "Takes a path \"/foo/:bar/:what\" and returns the regex #\"/foo/([^/]*)/([^/]*)\""
  12.   (re-pattern
  13.     (clojure.string/join (interpose \/ (map #(if (re-matches #"^:.*" %) "([^/]*)" %)
  14.                                             (clojure.string/split path-pattern #"/"))))))
  15.  
  16. (defn matcher [path-pattern]
  17.   "Takes a simple route pattern, such as /foo/:bar/:baz, and returns a string matching function that, if it's argument matches
  18. returns a map with the named parameters"
  19.   (let [re (to-regex path-pattern)
  20.         imap (index-map path-pattern)]
  21.     (fn [str]
  22.       (if-let [matches (re-matches re str)]
  23.         (apply hash-map (mapcat (fn [x] [(second x) (get matches (first x))]) imap))))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement