Clojure: How to Hook into Defrecord Constructor -
the title of question may on specify implementation, idea simple, want create , record, or similar, map type declared deftype, etc... want create object string id , int age, want convert id uuid , age int if not already. how do idiomatically?
so far have this:
(let [item (my.model/map->item { :id (uuid/fromstring "62c36092-82a1-3a00-93d1-46196ee77204") :age (int 6)})])
but dont want both of operations every time create item, want logic in 1 place. make auxiliary function this, there built in support in deftype or defrecord?
it's easiest use function takes input map , constructs item that.
(defn make-item [{:keys [id age] :as input}] {:pre [(string? id) (number? age)]} (-> input (update-in [:id] #(uuid/fromstring %)) (update-in [:age] int) my.model/map->item))
this scale nicely need more keys or stricter constraints, , adapts other record types.
Comments
Post a Comment