Created
February 10, 2017 17:04
-
-
Save tcoupland/5aaf2e7ae7a38af873d8ebec07db56f7 to your computer and use it in GitHub Desktop.
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
(defn -bool? | |
[x] | |
(cond | |
(boolean? x) x | |
(string? x) (case x | |
("true" "TRUE" "t" "T") true | |
("false" "FALSE" "f" "F") false | |
:clojure.spec/invalid) | |
:else :clojure.spec/invalid)) | |
(def bool? | |
(s/with-gen (s/conformer -bool? identity) | |
(constantly (gen/boolean)))) | |
(s/def ::b bool?) | |
(s/def ::bmv (s/cat :b ::b)) | |
(s/conform ::bmv ["true"]) | |
;; => {:b true} | |
(s/unform ::bmv (s/conform ::bmv ["true"])) | |
;; => (true) | |
(s/unform ::bmv (s/conform ::bmv ["foo"])) | |
;; => contains? not supported on type: clojure.lang.Keyword | |
(defn coerce | |
[spec data] | |
(let [conformed (s/conform spec data)] | |
(if (= :clojure.spec/invalid conformed) | |
conformed | |
(s/unform spec conformed)))) | |
(coerce ::bmv ["t"]) | |
;; => (true) | |
(s/valid? ::bmv (coerce ::bmv ["t"])) | |
;; => true | |
(coerce ::bmv ["foo"]) | |
;; => :clojure.spec/invalid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment