Skip to content

Instantly share code, notes, and snippets.

@gdeer81
Forked from Deraen/spec-coercion.clj
Last active January 23, 2017 12:49
Show Gist options
  • Save gdeer81/0c2406cf58cde5785794b1153b65b1f2 to your computer and use it in GitHub Desktop.
Save gdeer81/0c2406cf58cde5785794b1153b65b1f2 to your computer and use it in GitHub Desktop.
Clojure.spec coercion test
(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