简体   繁体   中英

How to test if key is UUID in clojure

I'm trying to check whether a keyword is an UUID. It should look like this (which is not working):

{:70342332-7f99-417a-b864-9006de62ae05 {:a 1 b: 2}} => (just {uuid? {:a 1 :b 2}})

What are other ways to test it?

Using Midje 1.9.

A clean way to archive what you need is this:

(defn keyword->uuid [kw]
     (try
      (java.util.UUID/fromString (name kw))
     (catch Exception e nil)))

If the keyword is convertible to the uuid object it will be converted and returned (note that any non-null return value is true so you can use this function both as a converter and a test). Otherwise the result would be nil:

user=> (keyword->uuid :dasdsa)
nil
user=> (keyword->uuid :70342332-7f99-417a-b864-9006de62ae05)
#uuid "70342332-7f99-417a-b864-9006de62ae05"

Note that :70342332-7f99-417a-b864-9006de62ae05 is not a UUID, it's a keyword. More generally speaking, a keyword is in Clojure a keyword, nothing else, regardless of what the string of characters looks like.

One way to achieve what you want is to take the name of the keyword and then read this string explicitly as a UUID:

user=> (uuid? (read-string (str "#uuid \"" (name :70342332-7f99-417a-b864-9006de62ae05) "\"")))
true

You can then write your own Midje checker using this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM