Created
October 31, 2012 14:57
-
-
Save jcromartie/3987491 to your computer and use it in GitHub Desktop.
arc challenge in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns arc.core | |
(:use compojure.core) | |
(:require [compojure.route :as route] | |
[compojure.handler :as handler] | |
[ring.util.response :as response] | |
[ring.adapter.jetty :as jetty])) | |
(def route-map (ref {})) | |
(def ^:dynamic *params* nil) | |
(defn handle [req] | |
(if-let [user-handler (@route-map (:uri req))] | |
(binding [*params* (:params req)] | |
(user-handler req)) | |
"Oh no! No user route found.")) | |
;; our main handler is just a wrapper around the dynamic route map handler | |
(def handler (handler/site (GET "/*" [:as req] (handle req)))) | |
(defn start-server | |
[] | |
(def server (jetty/run-jetty #'handler {:join? false :port 8080}))) | |
;; Web callback creation | |
(defn install-handler | |
[path handler] | |
(dosync (alter route-map assoc path handler))) | |
(defn web-callback | |
"Installs handler for supplied callback function and returns URL" | |
[f] | |
(let [path (str "/" (gensym "callback"))] | |
(install-handler path f) | |
path)) | |
;; My version of Arc's web app macros | |
(defmacro defop | |
[name & fn-tail] | |
`(install-handler (str "/" '~name) (fn ~@fn-tail))) | |
(defmacro aform [callback & body] | |
`(let [callback-path# (web-callback (fn [_#] ~callback))] | |
(format "<form action=\"%s\">%s</form>" callback-path# (with-out-str ~@body)))) | |
(defmacro onlink [text & callback-body] | |
`(let [url# (web-callback (fn [_#] (with-out-str ~@callback-body)))] | |
(format "<a href=\"%s\">%s</a>" url# ~text))) | |
(defn input [name] | |
(println (format "<input name=\"%s\">" name))) | |
(defn submit [] | |
(println "<input type=\"submit\">Submit</input>")) | |
(defn arg | |
[name] | |
(get *params* name)) | |
;; And now, for the Arc Challenge | |
(defop said [req] | |
(aform (let [text (arg :foo)] | |
(onlink "click here" (println "you said: " text))) | |
(input "foo") | |
(submit))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment