Permalink
Browse files

Add ring.static middleware, a filtering wrapper around ring.file that…

… minimizes filesystem calls
  • Loading branch information...
1 parent 044310f commit 35fd1b2921c3d105123601a4e856536b455a52dc @mmcgrana committed Jan 13, 2009
Showing with 38 additions and 0 deletions.
  1. +18 −0 src/ring/static.clj
  2. +1 −0 test/ring/assets/bars/foo.html
  3. +18 −0 test/ring/static_test.clj
  4. +1 −0 test/run.clj
View
18 src/ring/static.clj
@@ -0,0 +1,18 @@
+(ns ring.static
+ (:require ring.file)
+ (:use ring.utils))
+
+(defn wrap
+ "Like ring.file, but takes an additional statics, a coll of Strings that will
+ be used to test incoming requests uris. If the uri begins with any of the
+ strings in statics, the middleware will check to see if a files can be served
+ from the public-dir before proxying back to the given app; if the uri does not
+ match the re, proxies the request directly back to the app without touching the
+ filesystem."
+ [public-dir statics app]
+ (let [app-with-file (ring.file/wrap public-dir app)]
+ (fn [req]
+ (let [uri (:uri req)]
+ (if (some #(.startsWith uri %) statics)
+ (app-with-file req)
+ (app req))))))
View
1 test/ring/assets/bars/foo.html
@@ -0,0 +1 @@
+foo
View
18 test/ring/static_test.clj
@@ -0,0 +1,18 @@
+(ns ring.static-test
+ (:use clj-unit.core ring.static)
+ (:import java.io.File))
+
+(def public-dir (File. "test/ring/assets"))
+(def foo-html (File. "test/ring/assets/foo.html"))
+(def nested-foo-html (File. "test/ring/assets/bars/foo.html"))
+(def statics ["/foo.html" "/bars/"])
+
+(def app (ring.static/wrap public-dir statics (constantly {:body :dynamic})))
+
+(defn app-response-body [uri]
+ (:body (app {:request-method :get :uri uri})))
+
+(deftest "wrap"
+ (assert= foo-html (app-response-body "/foo.html"))
+ (assert= nested-foo-html (app-response-body "/bars/foo.html"))
+ (assert= :dynamic (app-response-body "/not/static")))
View
1 test/run.clj
@@ -5,5 +5,6 @@
'ring.lint-test
'ring.file-test
'ring.file-info-test
+ 'ring.static-test
'ring.reload-test
'ring.backtrace-test)

0 comments on commit 35fd1b2

Please sign in to comment.