Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@venantius

This comment has been minimized.

Copy link

commented Oct 22, 2016

Thanks for putting this up; I found the actual documentation on the use of conformers sort of impossible to parse.

@gdeer81

This comment has been minimized.

Copy link

commented Jan 4, 2017

I fixed your try/catch block if you want to pull in my changes
https://gist.github.com/gdeer81/0c2406cf58cde5785794b1153b65b1f2

I have this thing about example code being repl ready. =)

@wilkerlucio

This comment has been minimized.

Copy link

commented Jul 25, 2017

Also, check the Spec Coerce project, it does spec inference to coerce your data and supports a custom coerce dictionary: https://github.com/wilkerlucio/spec-coerce

@codeasone

This comment has been minimized.

Copy link

commented Jan 31, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.