Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metaprogramming with clojure.spec values?

I've been trying out clojure.spec, and one idea I have for how to use it is to generate the UI for editing an instance of the map I'm specifying. For example, it might generate a web form with a datepicker field for a key that's specified to be a date, that kind of thing.

There is a get-spec method in the library, but it seems like there are no functions that operate on specifications-as-values in the way I need. Is there some way to do things like take a map spec and get back the required keys for that map as a vector? Is this kind of metaprogramming with specifications outside of the intended use case of clojure.spec?

like image 800
Derek Thurn Avatar asked Jan 15 '17 02:01

Derek Thurn


1 Answers

Metaprogramming with specs is definitely within the intended use case of clojure.spec.

We have not yet released (but have written and intend to) specs for spec forms themselves. With these, it is possible to conform a spec form itself and get back a data structure representing the spec which can be used to (for example), grab the required keys from a map spec.

Conforming with a ::spec spec might look something like this:

user=> (s/def ::name string?)
:user/name
user=> (s/def ::m (s/keys :req [::name]))
:user/m
user=> (s/conform ::spec (s/form ::m))
[:form {:s clojure.spec/keys, :args {:req [[:key :user/name]]}}]

You could then pluck the set of keys out of that structure.

like image 117
Alex Miller Avatar answered Dec 14 '22 23:12

Alex Miller