Permalink
Browse files

Introduce ring.branch, add both ring.branch and related ring.static t…

…o README.
  • Loading branch information...
1 parent 39bc29b commit 843c0a92e418223a66513cba7348fe26f235a432 @mmcgrana committed Jan 15, 2009
Showing with 42 additions and 0 deletions.
  1. +2 −0 README.textile
  2. +24 −0 src/ring/branch.clj
  3. +15 −0 test/ring/branch_test.clj
  4. +1 −0 test/run.clj
View
@@ -28,8 +28,10 @@ To see a more sophisticated Ring app, run:
h2. All Available Libs
* @ring.jetty@: Handler for the Jetty webserver.
+ * @ring.branch@: Middleware that proxies to one of multiple backing apps depending on the request uri.
* @ring.file@: Middleware that serves static files out of a public directory.
* @ring.file-info@: Middleware that augments response headers with info about File responses.
+ * @ring.static@: Middleware that serves static files with specified prefixes out of a public directory.
* @ring.dump@: Endpoint that dumps the Ring requests as HTML responses for debugging.
* @ring.show-exceptions@: Middleware that catches exceptions and displays readable backtraces for debugging.
* @ring.reload@: Middleware to automatically reload selected libs before each requests, minimizing server restarts.
View
@@ -0,0 +1,24 @@
+(ns ring.branch)
+
+(defn wrap
+ "Returns an app that proxies to one of several possible backing apps depending
+ on the beginning of the request uri.
+ Should be passed an odd number of arguments - the inital pairs of arguments
+ indicate the branching conditions and corresponding apps, and the last
+ argument the fallback app that will be invoked if none of the branching
+ conditions are met:
+
+ (wrap [\"/javascripts\" \"stylesheets\"] static-app
+ [\"/blog\"] blog-app
+ dynamic-app)"
+ [& branching]
+ (let [fallback (last branching)
+ branch-logic
+ (map (fn [[prefixes branch]]
+ (fn [req]
+ (let [uri (:uri req)]
+ (if (some #(.startsWith uri %) prefixes) (branch req)))))
+ (partition 2 branching))]
+ (fn [req]
+ (or (some #(% req) branch-logic)
+ (fallback req)))))
@@ -0,0 +1,15 @@
+(ns ring.branch-test
+ (:use clj-unit.core ring.branch))
+
+(def wrapped
+ (wrap ["/javascripts" "/stylesheets"] (fn [req] [req :static])
+ ["/blog"] (fn [req] [req :blog])
+ (fn [req] [req :dynamic])))
+
+(deftest "wrap"
+ (let [req {:uri "/stylesheets"}]
+ (assert= [req :static] (wrapped req)))
+ (let [req {:uri "/blog/foo"}]
+ (assert= [req :blog] (wrapped req)))
+ (let [req {:uri "/foo/blog"}]
+ (assert= [req :dynamic] (wrapped req))))
View
@@ -6,5 +6,6 @@
'ring.file-test
'ring.file-info-test
'ring.static-test
+ 'ring.branch-test
'ring.reload-test
'ring.backtrace-test)

0 comments on commit 843c0a9

Please sign in to comment.