Created
April 29, 2013 00:44
-
-
Save mwmitchell/5479064 to your computer and use it in GitHub Desktop.
mapping-macros
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
(defmacro field+ [n fields & forms] | |
(let [f (mapv keyword fields) | |
args {:keys fields :as '$doc}] | |
`(hash-map ~n {:fields ~f | |
:fn (let [~'$fields ~f] | |
(fn [~args] ~@forms))}))) | |
(defmacro defmodel [name & forms] | |
`(def ~name (merge {} ~@forms))) | |
(defn field [fname & [f]] | |
{fname {:fields [(or f fname)] :fn (fn [d] (get d (or f fname)))}}) | |
(defn mapdoc [model doc] | |
(reduce-kv #(assoc %1 %2 ((:fn %3) doc)) {} model)) | |
(defmodel hotel | |
(field :udicode) | |
(field :name) | |
(field :telephone :tele) | |
(field+ :address [address1 address2 city region country] | |
(select-keys $doc $fields))) | |
(mapdoc hotel {:name "The Omni" | |
:tele "123-123-1234" | |
:udicode "123-456-789" | |
:address1 "100 1st St." | |
:address2 nil | |
:city "Charlottesville" | |
:region "Virginia" | |
:country "United States"}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment