Skip to content

Instantly share code, notes, and snippets.

@flyingmachine
Created December 16, 2012 21:33
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 flyingmachine/4313380 to your computer and use it in GitHub Desktop.
Save flyingmachine/4313380 to your computer and use it in GitHub Desktop.
so far, only used in a web app when I want to update a subset of available fields. eg when changing a password
(defentity user
(has-many post)
(has-many comment)
;; todo move user param transform function here
(prepare
(fn [attributes]
(-> (transform-when-key-exists
attributes
{:password #(creds/hash-bcrypt %)
:receive_comment_notifications #(= % "on")
:receive_newsletter #(= % "on")})
(assoc :roles (str [:user])))))
(transform #(deserialize % :roles)))
(defentity user
(has-many post)
(has-many comment)
;; todo move user param transform function here
(prepare
(fn [attributes]
(-> (if (:password attributes)
(assoc attributes :password (creds/hash-bcrypt (:password attributes)))
attributes)
(assoc :roles (str [:user])))))
(transform #(deserialize % :roles)))
(deftest transform-when-key-exists-test
(testing "Returns a map with all transformations applied"
(is (= (transform-when-key-exists
{:a 1 :b 2}
{:a #(inc %)
:c #(inc %)})
{:a 2 :b 2}))))
(defn transform-when-key-exists
"(transform-when-key-exists
{:a 1
:b 2}
{:a #(inc %)
:c #(inc %)})
=> {:a 2 :b 2}"
[source transformations]
(reduce
(fn [m x]
(merge m
(let [[key value] x]
(if-let [transform (get transformations key)]
{key (transform value)}
x))))
{}
source))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment