diff --git a/CHANGES.markdown b/CHANGES.markdown index 449e163..5b9d069 100644 --- a/CHANGES.markdown +++ b/CHANGES.markdown @@ -5,6 +5,7 @@ * Remove old examples. These dependet on an ancient clojurescript version which blocked updating some dependencies * Update clojure versions in the build matrix. +* Allow `defresource` to have a docstring (#305) ## Bugs fixed diff --git a/src/liberator/core.clj b/src/liberator/core.clj index 754b1f3..d2f71b2 100644 --- a/src/liberator/core.clj +++ b/src/liberator/core.clj @@ -615,17 +615,24 @@ (fn [request] (run-resource request (get-options kvs)))) -(defmacro defresource [name & kvs] - (if (vector? (first kvs)) - (let [args (first kvs) - kvs (rest kvs)] - ;; Rather than call resource, create anonymous fn in callers namespace for better debugability. - `(defn ~name [~@args] - (fn [request#] - (run-resource request# (get-options (list ~@kvs)))))) - `(def ~name - (fn [request#] - (run-resource request# (get-options (list ~@kvs))))))) +(defmacro defresource [name & resource-decl] + (let [[docstring resource-decl] (if (string? (first resource-decl)) + [(first resource-decl) (rest resource-decl)] + [nil resource-decl]) + [args kvs] (if (vector? (first resource-decl)) + [(first resource-decl) (rest resource-decl)] + [nil resource-decl]) + ;; Rather than call `resource` directly, create an anonymous + ;; function in the caller's namespace for better debugability. + resource-fn `(fn [request#] + (run-resource request# (get-options (list ~@kvs))))] + (if args + (if docstring + `(defn ~name ~docstring [~@args] ~resource-fn) + `(defn ~name [~@args] ~resource-fn)) + (if docstring + `(def ~name ~docstring ~resource-fn) + `(def ~name ~resource-fn))))) (defn by-method "returns a handler function that uses the request method to diff --git a/test/test_defresource.clj b/test/test_defresource.clj index 0bdfa9b..bd0f34f 100644 --- a/test/test_defresource.clj +++ b/test/test_defresource.clj @@ -22,6 +22,10 @@ :service-available? with-service-available?-multimethod* :handle-ok (fn [_] "with-service-available?-multimethod")) +(defresource with-docstring + "This is a fancy docstring." + :handle-ok (fn [_] "OK")) + (defresource without-param :handle-ok (fn [_] (format "The text is %s" "test"))) @@ -56,6 +60,9 @@ :handle-ok (str request)) (facts "about defresource" + (fact "a docstring can be optionally provided" + (with-docstring {:request-method :get}) + => {:headers {"Content-Type" "text/plain;charset=UTF-8"}, :body "OK", :status 200}) (fact "its simple form should behave as it always has" (without-param {:request-method :get}) => {:headers {"Content-Type" "text/plain;charset=UTF-8"}, :body "The text is test", :status 200}