Skip to content

Instantly share code, notes, and snippets.

@ossareh
Created January 5, 2011 23:16
Show Gist options
  • Save ossareh/767204 to your computer and use it in GitHub Desktop.
Save ossareh/767204 to your computer and use it in GitHub Desktop.
transform ratios to map and back again
(defmulti transform-ratio
"Transforms Ratios to and from maps. Passes other values through without changing them unless they are of type clojure.lang.Ratio or clojure.lang.PersistenArrayMap. In the case of a map they must be annotated with :t \"ratio\" otherwise they'll get passed through too"
class)
(defmethod transform-ratio :default [v] v)
(defmethod transform-ratio clojure.lang.Ratio [value]
{:n (numerator value)
:d (denominator value)
:t "ratio"})
(defmethod transform-ratio clojure.lang.PersistentArrayMap [value]
(if (and (contains? value :t)
(= "ratio" (:t value)))
(/ (:n value) (:d value))
value))
;; riak helper
(defn- put [bucket key data]
(let [bucket (name bucket)
data (postwalk transform-ratio data)]
(riak/put rc bucket key
{:value (.getBytes (json/json-str data))
:content-type "application/json"})))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment