Created
December 16, 2012 21:33
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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})))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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