Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (defmacro check-let [b-vec & body]
- (if-not (empty? b-vec)
- (let [v (take 3 b-vec)
- r (apply vector (drop 3 b-vec))]
- `(if-let [~@(take 2 v)]
- (check-let ~r ~@body)
- ~(nth v 2)))
- `(do ~@body)))
- ;; turns this:
- (if-let [a 1]
- (if-let [b 2]
- (if-let [c 3]
- (if-let [d 4]
- {:success true :result (+ a b c d)}
- {:success false :message "Couldn't find D"})
- {:success false :message "Couldn't find C"})
- {:success false :message "Couldn't find B"})
- {:success false :message "Couldn't find A"})
- ;; into this:
- (check-let [a 1 {:success false :message "Couldn't find A"}
- b 2 {:success false :message "Couldn't find B"}
- c 3 {:success false :message "Couldn't find C"}
- d 4 {:success false :message "Couldn't find D"}]
- {:success true :result (+ a b c d)})
- ;;
- ;; real world example: web request handler that inserts a new record
- ;;
- ;; this:
- (defn new-addition [thought-id]
- (fn [req]
- (if-let [addition-text (:comment (:params req))]
- (if-let [thought (find-thought! thought-id)]
- (if-let [user (current-user! req)]
- (let [addition (make-addition addition-text thought user)]
- (insert! :additions addition)
- (json-success (merge addition {:html (render-addition addition)})))
- (json-fail "No valid user."))
- (json-fail "No thought by that id."))
- (json-fail "Text can't be blank."))))
- ;; into this:
- (defn new-addition [thought-id]
- (fn [req]
- (check-let [addition-text (:comment (:params req)) (json-fail "Text can't be blank.")
- thought (find-thought! thought-id) (json-fail "No thought by that id.")
- user (current-user! req) (json-fail "No valid user.")]
- (let [addition (make-addition addition-text thought user)]
- (insert! :additions addition)
- (json-success addition)))))
Add Comment
Please, Sign In to add comment