Skip to content

Instantly share code, notes, and snippets.

@jcromartie
Created October 31, 2012 14:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcromartie/3987491 to your computer and use it in GitHub Desktop.
Save jcromartie/3987491 to your computer and use it in GitHub Desktop.
arc challenge in Clojure
(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