Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Extended response/render to include the request and handle more types

  • Loading branch information...
commit b4165214411a73dfef35d5cb375ea0846c2e987e 1 parent 6d60382
@weavejester authored
View
2  src/compojure/core.clj
@@ -54,7 +54,7 @@
(if-let [route-params# (route-matches route# request#)]
(let [request# (#'assoc-route-params request# route-params#)]
(bind-request request# ~bindings
- (render (do ~@body)))))))))
+ (render request# (do ~@body)))))))))
(defn routes
"Create a Ring handler by combining several handlers into one."
View
33 src/compojure/response.clj
@@ -1,18 +1,31 @@
(ns compojure.response
"Methods for generating Ring response maps"
- (:import java.util.Map))
+ (:import java.util.Map
+ java.io.File
+ [clojure.lang IDeref IFn]))
(defmulti render
- "Turns its argument into an appropriate response"
- type)
+ "Given the request map and an arbitrary value x, turn x into a valid HTTP
+ response map. Dispatches on the type of x."
+ (fn [_ x] (type x)))
-(defmethod render nil [_] nil)
+(defmethod render nil [_ _] nil)
-(defmethod render String [html-string]
- {:status 200
+(defmethod render String [_ html]
+ {:status 200
:headers {"Content-Type" "text/html"}
- :body html-string})
+ :body html})
-(defmethod render Map [a-map]
- (merge {:status 200, :headers {}, :body ""}
- a-map))
+(defmethod render Map [_ m]
+ (merge {:status 200, :headers {}, :body ""} m))
+
+(defmethod render IFn [request handler]
+ (render (handler request)))
+
+(defmethod render IDeref [_ r]
+ (render (deref r)))
+
+(defmethod render File [_ f]
+ {:status 200, :headers {}, :body f})
+
+(prefer-method render Map IFn)
View
12 test/compojure/response_test.clj
@@ -0,0 +1,12 @@
+(ns compojure.response-test
+ (:use clojure.test)
+ (:require [compojure.response :as response]))
+
+(deftest response-with-nil
+ (is (nil? (response/render {} nil))))
+
+(deftest response-with-string
+ (is (= (response/render {} "<h1>Foo</h1>")
+ {:status 200
+ :headers {"Content-Type" "text/html"}
+ :body "<h1>Foo</h1>"})))
Please sign in to comment.
Something went wrong with that request. Please try again.