Skip to content

Instantly share code, notes, and snippets.

@bhb
Created February 4, 2018 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhb/5222914641bcdd08d07b7d930e388d89 to your computer and use it in GitHub Desktop.
Save bhb/5222914641bcdd08d07b7d930e388d89 to your computer and use it in GitHub Desktop.
Custom printer for Expound
(require '[clojure.spec.alpha :as s])
(require '[expound.alpha :as expound])
;; For a cat spec...
(s/def :ex/my-spec (s/cat
:conn any?
:x int?
:y int?))
;; with the default printer, valid values won't be printed ...
(binding [s/*explain-out* expound/printer]
(s/explain :ex/my-spec [::fake-connection-obj-that-should-not-be-printed 1 "2"]))
;; -- Spec failed --------------------
;; [... ... "2"]
;; ^^^
;; should satisfy
;; int?
;;;;;;;;;;;;;;;;
;; You can set up a printer to display valid values...
(binding [s/*explain-out* (expound/custom-printer {:show-valid-values? true})]
(s/explain :ex/my-spec [::fake-connection-obj-that-should-not-be-printed 1 "2"]))
;; -- Spec failed --------------------
;; [:expound.alpha/fake-connection-obj-that-should-not-be-printed
;; 1
;; "2"]
;; ^^^
;; should satisfy
;; int?
;; But what if you want to display most valid values, but display
;; a more succinct value for the first arg? You can provide a custom printer...
(defn my-value-printer [spec-name form path value]
(expound/value-in-context
{:show-valid-values? true}
spec-name
(assoc form 0 :fake-conn) ;; <- a more succinct version
path
value))
(binding [s/*explain-out* (expound/custom-printer {:value-str-fn my-value-printer})]
(s/explain :ex/my-spec [::fake-connection-obj-that-should-not-be-printed 1 "2"]))
;; -- Spec failed --------------------
;; [:fake-conn 1 "2"]
;; ^^^
;; should satisfy
;; int?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment