Skip to content

Commit

Permalink
Added route/resources function and unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
weavejester committed Sep 14, 2010
1 parent 583236e commit 5e3543f
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/compojure/route.clj
@@ -1,6 +1,6 @@
(ns compojure.route (ns compojure.route
(:use compojure.core (:use compojure.core
[ring.util.response :only (file-response)] [ring.util.response :only (file-response resource-response)]
[ring.util.codec :only (url-decode)])) [ring.util.codec :only (url-decode)]))


(defn- add-wildcard (defn- add-wildcard
Expand All @@ -9,13 +9,25 @@
(str path (if (.endsWith path "/") "*" "/*"))) (str path (if (.endsWith path "/") "*" "/*")))


(defn files (defn files
"A route for serving static files from a directory." "A route for serving static files from a directory. Accepts the following
keys:
:root - the root path where the files are stored. Defaults to 'public'."
[path & [options]] [path & [options]]
(GET (add-wildcard path) {{file-path "*"} :params} (GET (add-wildcard path) {{file-path "*"} :params}
(let [options (merge {:root "public"} options)] (let [options (merge {:root "public"} options)]
(file-response file-path options)))) (file-response file-path options))))


(defn resources
"A route for serving resources on the classpath. Accepts the following
keys:
:root - the root prefix to get the resources from. Defaults to 'public'."
[path & [options]]
(GET (add-wildcard path) {{resource-path "*"} :params}
(let [options (merge {:root "public"} options)]
(resource-response resource-path options))))

(defn not-found (defn not-found
"A route that returns a 404 not found response." "A route that returns a 404 not found response, with its argument as the
response body."
[body] [body]
(ANY "*" [] {:status 404, :body body})) (ANY "*" [] {:status 404, :body body}))
15 changes: 15 additions & 0 deletions test/compojure/test/route.clj
@@ -0,0 +1,15 @@
(ns compojure.test.route
(:use clojure.test
[clojure.contrib.duck-streams :only (slurp*)])
(:require [compojure.route :as route]))

(deftest not-found-route
(let [response ((route/not-found "foo") {})]
(is (= (:status response) 404))
(is (= (:body response) "foo"))))

(deftest resources-route
(let [route (route/resources "/foo" {:root "resources"})
response (route {:request-method :get, :uri "/foo/test.txt"})]
(is (= (:status response) 200))
(is (= (slurp* (:body response)) "foobar\n"))))
1 change: 1 addition & 0 deletions test/resources/test.txt
@@ -0,0 +1 @@
foobar

0 comments on commit 5e3543f

Please sign in to comment.