ClojureDocs

Nav

Namespaces

datafy

  • (datafy x)
Attempts to return x as data.
datafy will return the value of clojure.core.protocols/datafy. If
the value has been transformed and the result supports
metadata, :clojure.datafy/obj will be set on the metadata to the
original value of x, and :clojure.datafy/class to the name of the
class of x, as a symbol.
3 Examples
;; default impl is the identity
(datafy {:message "Hello"})
=>
{:message "Hello"}

;; exceptions default datafy impl is `Throwable->map`
(datafy (ex-info "An Exception" {:msg "something went wrong"}))
{:cause "An Exception",
 :data {:msg "something went wrong"}
 :via
 [{:type clojure.lang.ExceptionInfo,
   :message "An Exception",
   :data {:msg "something went wrong"},
   :at [user$eval16337 invokeStatic "form-init3462716552974711523.clj" 120]}],
 :trace
 [[user$eval16337 invokeStatic "form-init3462716552974711523.clj" 120]
  [user$eval16337 invoke "form-init3462716552974711523.clj" 120]
  [clojure.lang.Compiler eval "Compiler.java" 7181]
  ,,,
  [clojure.lang.AFn run "AFn.java" 22]
  [java.lang.Thread run "Thread.java" 833]]}
;; add a (bogus) Datafy implementation for java.util.Date

(require '[clojure.core.protocols :as p])
(require '[clojure.datafy :as d])

(extend-protocol p/Datafiable
  java.util.Date
  (datafy [d]
    {:type 'Date
     :timestamp (.getTime d)}))

(d/datafy (java.util.Date.))
;;=> {:type Date, :timestamp 1641145865991}
;; adding a data representation to a java.io.File

(require '[clojure.core.protocols :as p])
(require '[clojure.datafy :as d])

(extend-protocol p/Datafiable
  java.io.File
  (datafy [f]
      {:exists (.exists f)
       :length (.length f)
       :last-modified (.lastModified f)
       :path (.toString f)})))

(d/datafy (java.io.File. "/home/alfred/todo.txt"))
;;=> {:exists true,
;;    :length 28850,
;;    :last-modified 1641082627553,
;;    :path "/home/alfred/todo.txt"}

;; java.io.File is availiable with (:clojure.datafy/obj (meta ...))
See Also
No see-alsos for clojure.datafy/datafy
0 Notes
No notes for datafy