Permalink
Browse files

Added resource-response function

  • Loading branch information...
1 parent 0e01b20 commit 7f3cdeeaafc41310bd9485b59e653fadcadb621b @weavejester weavejester committed Jul 6, 2010
Showing with 24 additions and 1 deletion.
  1. +12 −0 ring-core/src/ring/util/response.clj
  2. +12 −1 ring-core/test/ring/util/response_test.clj
View
12 ring-core/src/ring/util/response.clj
@@ -54,6 +54,18 @@
(if-let [file (get-file filepath opts)]
(response file)))
+(defn resource-response
+ "Returns a Ring response to serve a packaged resource, or nil if the
+ resource does not exist.
+ Options:
+ :root - take the resource relative to this root"
+ [path & [opts]]
+ (let [opts (apply hash-map opts)
+ path (str (opts :root "") path)
+ loader (clojure.lang.RT/baseLoader)]
+ (if-let [resource (.getResourceAsStream loader path)]
+ (response resource))))
+
(defn status
"Returns an updated Ring response with the given status."
[resp status]
View
13 ring-core/test/ring/util/response_test.clj
@@ -1,6 +1,7 @@
(ns ring.util.response-test
(:use clojure.test
- ring.util.response))
+ ring.util.response
+ [clojure.contrib.duck-streams :only (slurp*)]))
(deftest test-redirect
(is (= {:status 302 :headers {"Location" "http://google.com"} :body ""}
@@ -16,3 +17,13 @@
(deftest test-content-type
(is (= {:status 200 :headers {"Content-Type" "text/html" "Content-Length" "10"}}
(content-type {:status 200 :headers {"Content-Length" "10"}} "text/html"))))
+
+(deftest test-resource-response
+ (let [resp (resource-response "/ring/util/response_test.clj")]
+ (is (= (resp :status) 200))
+ (is (= (resp :headers) {}))
+ (is (.startsWith (slurp* (resp :body))
+ "(ns ring.util.response-test"))))
+
+(deftest test-missing-resource
+ (is (nil? (resource-response "/missing/resource.clj"))))

0 comments on commit 7f3cdee

Please sign in to comment.