Skip to content

Instantly share code, notes, and snippets.

@myguidingstar-zz
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save myguidingstar-zz/ad29083023130817eb01 to your computer and use it in GitHub Desktop.
Save myguidingstar-zz/ad29083023130817eb01 to your computer and use it in GitHub Desktop.
(ns strange.macros
#+cljs (:require-macros [cemerick.cljs.test :refer [is deftest]]
[strange.macros :refer [my-response edn]]))
;; I want an abstraction over a javascript library. These macros are simplified versions
#+clj
(defmacro my-response
[x]
(let [{:keys [status headers body]} x]
`(+ ~status ~body)))
#+clj
(defmacro edn
;; ([body] `(edn 200 ~body))
([status body]
{:status status
:headers {"Content-Type" "application/edn"}
:body `(pr-str ~body)}))
#+cljs
(deftest dummy-macro-tests
;; I use (+ [] {}) just to make sure the code is evaluated in javascript
(is (= (my-response (edn [] {})) "[]{}")))
;; This is what I do with the real my-response
(comment
;; inside a request handler
(my-response response-object {:status 200 :headers {"Content-type" "..."} {:hello "world"}})
(my-response response-object (edn {:hello "world"}))
)
@myguidingstar-zz
Copy link
Author

Compiler yells this:

Caused by: java.lang.IllegalArgumentException: No value supplied for key: {}

@myguidingstar-zz
Copy link
Author

this one works

#+clj
(defmacro parent
  "Given a map or a macro that expand to a map, do some calculation."
  [x]
  (let [{:keys [a b]} (macroexpand x)]
    `(+ ~a ~b)))

#+clj
(defmacro child
  "A macro that returns a map"
  [body]
  {:a [] :b `(pr-str ~(macroexpand body))})

#+cljs
(deftest dummy-macro-tests
  (is (= (parent {:a 2 :b 2}) 4))
  (is (= (parent (child {:hello "world"})) "[]{:hello \"world\"}"))
)

@myguidingstar-zz
Copy link
Author

It turns out that cljsbuild auto sometimes compiles before cljx auto finishes which result the output javascript is a mix of old and new code. This macro itself is guiltless :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment