-
Notifications
You must be signed in to change notification settings - Fork 80
/
utils.clj
65 lines (52 loc) · 1.78 KB
/
utils.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
(ns tutorial.utils
(:require [net.cgrand.enlive-html :as html]
[clojure.java.io :as io])
(:use [ring.adapter.jetty :only [run-jetty]]
[ring.util.response :only [response file-response]]
[ring.middleware.reload :only [wrap-reload]]
[ring.middleware.file :only [wrap-file]]
[ring.middleware.stacktrace :only [wrap-stacktrace]]))
(def ^:dynamic *webdir* (str (.getCanonicalFile (io/file ".")) "/src/tutorial/"))
(defn render [t]
(apply str t))
(defn render-snippet [s]
(apply str (html/emit* s)))
(def render-to-response
(comp response render))
(defn page-not-found [req]
{:status 404
:headers {"Content-type" "text/html"}
:body "Page Not Found"})
(defn render-request [afn & args]
(fn [req] (render-to-response (apply afn args))))
(defn serve-file [filename]
(file-response
{:root *webdir*
:index-files? true
:html-files? true}))
(defn run-server* [app & {:keys [port] :or {port 8080}}]
(let [nses (if-let [m (meta app)]
[(-> (:ns (meta app)) str symbol)]
[])]
(println "run-server*" nses)
(run-jetty
(-> app
(wrap-file *webdir*)
(wrap-reload nses)
(wrap-stacktrace))
{:port port :join? false})))
(defmacro run-server [app]
`(run-server* (var ~app)))
(defmulti parse-int type)
(defmethod parse-int java.lang.Integer [n] n)
(defmethod parse-int java.lang.String [s] (Integer/parseInt s))
(defmacro maybe-substitute
([expr] `(if-let [x# ~expr] (html/substitute x#) identity))
([expr & exprs] `(maybe-substitute (or ~expr ~@exprs))))
(defmacro maybe-content
([expr] `(if-let [x# ~expr] (html/content x#) identity))
([expr & exprs] `(maybe-content (or ~expr ~@exprs))))
(defn pluralize [astr n]
(if (= n 1)
(str astr)
(str astr "s")))