Created
June 14, 2016 15:47
-
-
Save Deraen/6c686358da62e8ed4b3d19c82f3e786a to your computer and use it in GitHub Desktop.
Clojure.spec coercion test
This file contains hidden or 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
(ns spec-test.core | |
(:require [clojure.spec :as s])) | |
(defn x-integer? [x] | |
(if (integer? x) | |
x | |
(if (string? x) | |
(try | |
(integer/parseint x) | |
(catch exception e | |
:clojure.spec/invalid)) | |
:clojure.spec/invalid))) | |
(s/def ::user/name string?) | |
(s/def ::user/age (s/conformer x-integer?)) | |
(s/def ::user (s/keys :req [::user/name ::user/age])) | |
(s/conform ::user {::user/name "juho" ::user/age 9001}) | |
;; => {:user/name "juho", :user/age 9001} | |
(s/conform ::user {::user/name "juho" ::user/age "9001"}) | |
;; => {:user/name "juho", :user/age 9001} | |
(s/conform ::user {::user/name "juho" ::user/age "x9001"}) | |
;; => :clojure.spec/invalid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a helpful compared to the first example listed in https://clojuredocs.org/clojure.spec/conformer which is too cryptic for the uninitiated in my opinion.