Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;; note- path-pattern should escape any regex patterns first, but doesn't.
- (defn index-map [path-pattern]
- "Takes a path \"/foo/:bar/:what\" and returns the indices into the regex #\"/foo/([^/]*)/([^/]*)\""
- (zipmap (iterate inc 1)
- (map (comp keyword clojure.string/join rest)
- (filter #(re-matches #"^:.*" %)
- (clojure.string/split path-pattern #"/")))))
- (defn to-regex [path-pattern]
- "Takes a path \"/foo/:bar/:what\" and returns the regex #\"/foo/([^/]*)/([^/]*)\""
- (re-pattern
- (clojure.string/join (interpose \/ (map #(if (re-matches #"^:.*" %) "([^/]*)" %)
- (clojure.string/split path-pattern #"/"))))))
- (defn matcher [path-pattern]
- "Takes a simple route pattern, such as /foo/:bar/:baz, and returns a string matching function that, if it's argument matches
- returns a map with the named parameters"
- (let [re (to-regex path-pattern)
- imap (index-map path-pattern)]
- (fn [str]
- (if-let [matches (re-matches re str)]
- (apply hash-map (mapcat (fn [x] [(second x) (get matches (first x))]) imap))))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement