INDEX | HOME

Clojure helpers

Table of Contents

These are helpers and shortcuts for Clojure(Script) projects.

Not not all of them are my own original idea.

1. Clojure

1.1. dumping a large data structure

Just call debugdump with any number of strings as arguments.

(defn debugdump
  "concatenate and save to file"
  [& strings]
  (spit "/tmp/cljdebug.txt" (str (apply str strings) "\n")))

1.2. map-of

For when you need to put some variables into map format:

(defmacro map-of
  [& xs]
  `(hash-map ~@(mapcat (juxt keyword identity) xs)))

1.3. url encoding

Shortcut for URL encoding/decoding

(defn urlencode [foo]
  (java.net.URLEncoder/encode foo "UTF-8"))

(defn urldecode [foo]
  (java.net.URLDecoder/decode foo "UTF-8"))

1.4. ring debugging middleware

If you just want to see the entire request map:

(defn wrap-debug-reqmap
  "debug middleware to save the requestmap to a file so we can analyze"
  [handler comment]
  (fn [req]
    (when-not (string/includes? (:uri req) "favicon.ico")
      (let [timestamp (.toString (java.time.LocalDateTime/now))
            filename (str "reqlog/request-" comment "-" timestamp ".edn")]
        (clojure.pprint/pprint req (clojure.java.io/writer filename))))

    ; Call the handler and return its response
    (handler req)))

2. ClojureScript

2.1. logging to console

Just call log with any number of strings as arguments.

(defn log
  "concatenate and print to console"
  [& strings]
  ((.-log js/console) (reduce str strings)))

2.2. get by id/class

Simple shortcuts

(defn byid
  "shortcut for getting element by id"
  [id]
  (.getElementById js/document id))

(defn byclass
  "shortcut for getting element by class"
  [name]
  (.getElementsByClassName js/document name))

2.3. creating elements and appending children

Saves time rather than using the bare js functions.

(defn create-elem+
  "create an element and add attributes"
  [type & attrs]
  (let [newelem (.createElement js/document type)]
    (doseq [[a b] (partition 2 attrs)]
      (.setAttribute newelem a b))
    newelem))

(defn append-child+
  "append multiple children"
  [elem & children]
  (doseq [c children]
    (prn c)
    (.appendChild elem c)))

(comment
  (let [elem (create-elem+ "span" "class" "boop")]
   (append-child+ elem  (.createElement js/document "a")))
  )

Copyright 2023 Joseph Graham (joseph@xylon.me.uk)