Skip to content

Instantly share code, notes, and snippets.

@emidln
Created July 18, 2017 18:20
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 emidln/8da9d6240679bbb57080682b20d4ba98 to your computer and use it in GitHub Desktop.
Save emidln/8da9d6240679bbb57080682b20d4ba98 to your computer and use it in GitHub Desktop.
;; This buffer is for Clojure experiments and evaluation.
;; Press C-j to evaluate the last expression.
(defn parse-number
"Reads a number from a string. Returns nil if not a number."
[s]
(when (re-find #"^-?\d+\.?\d*([Ee]\+\d+|[Ee]-\d+|[Ee]\d+)?$" (.trim s))
(read-string s)))
(defn try-number-fallback-str
[num]
(cond
(integer? num) num ;; stop, we're an int
(number? num) (int num) ;; we can cast to an int
:else (let [n (parse-number num)] ;; let's see if we can get a num
(if (number? n)
(int n) ;; cast to an int
num)))) ;; fallback to original input
(def +str->int-coercions+
{s/Int try-number-fallback-str})
(s/defn json-coercion-matcher
"A matcher that coerces keywords and keyword enums from strings, and longs and doubles
from numbers on the JVM (without losing precision)"
[schema :- types/Map]
(or (+str->int-coercions+ schema)
(coerce/+json-coercions+ schema)
(coerce/keyword-enum-matcher schema)
(coerce/set-matcher schema)))
(defn env
"environ.core/env, but as a fn and not cached. Calling this often is slow, you should probably
cache it yourself in a component."
[]
(merge
;; These are technically private. I don't care.
(#'environ/read-env-file ".lein-env")
(#'environ/read-system-env)
(#'environ/read-system-props)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment