Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added context macro

  • Loading branch information...
commit ec835a1bb2fc1db961325336e1829e91139246e3 1 parent d8ee3fb
@weavejester authored
Showing with 33 additions and 1 deletion.
  1. +23 −0 src/compojure/core.clj
  2. +10 −1 test/compojure/test/core.clj
View
23 src/compojure/core.clj
@@ -118,6 +118,29 @@
[path args & body]
(compile-route nil path args body))
+(defn- remove-suffix [path suffix]
+ (subs path (- (count path) (count suffix))))
+
+(defn- set-context [request]
+ (let [uri (:uri request)
+ path (:path-info request uri)
+ context (or (:context request) "")
+ subpath (->> request :route-params :* (str "/"))]
+ (assoc request
+ :path-info subpath
+ :context (remove-suffix uri subpath))))
+
+(defmacro context
+ [path args & routes]
+ `(let [route# ~(prepare-route (str path "/*"))]
+ (fn [request#]
+ (if-let [route-params# (route-matches route# request#)]
+ (let [request# (-> request#
+ (#'assoc-route-params route-params#)
+ (#'set-context))]
+ (bind-request request# ~args
+ (routing request# ~@routes)))))))
+
(defn- middleware-sym [x]
(symbol (namespace x) (str "wrap-" (name x))))
View
11 test/compojure/test/core.clj
@@ -68,7 +68,16 @@
(GET "/bar" [] (is true) nil))
(request :get "/bar")))
-(deftest wrap
+(deftest context-test
+ (let [rs (context "/foo/:id" [id]
+ (GET "" [] "root")
+ (GET "/id" [] id)
+ (ANY "*" [] "rest"))]
+ (are [req body] (= (:body (rs req)) body)
+ (request :get "/foo/10/id") "10"
+ (request :get "/foo/10/bar") "rest")))
+
+(deftest wrap-test
(testing "wrap function"
(defn func1 [x] (inc x))
(let [wrapper (fn [f] (fn [x] (f (inc x))))]
Please sign in to comment.
Something went wrong with that request. Please try again.