๐จโ๐ป๐ฉโ๐ป
We have into our namespace example a .clj
with demands, we need to import it in another .clj
for handle the demands, like groupping by a keyword for example.
In clojure we define a namespace by (ns my-namespace)
db.clj:
(ns example.db)
(def demand {:user 15
:itens {:bag {:id :bag :quantity 3 :price 80}
:t-shirt {:id :t-shirt :quantity 3 :price 40}
:shoes {:id :shoes :quantity 3}}})
(def demand2 {:user 15
:itens {:bag {:id :bag :quantity 3 :price 80}
:t-shirt {:id :t-shirt :quantity 3 :price 40}
:shoes {:id :shoes :quantity 3}}})
(def demand3 {:user 15
:itens {:bag {:id :bag :quantity 3 :price 80}
:t-shirt {:id :t-shirt :quantity 3 :price 40}
:shoes {:id :shoes :quantity 3}}})
(def demand4 {:user 11
:itens {:bag {:id :bag :quantity 2 :price 80}
:t-shirt {:id :t-shirt :quantity 3 :price 40}
:shoes {:id :shoes :quantity 7}}})
(def demand5 {:user 11
:itens {:bag {:id :bag :quantity 5 :price 80}
:t-shirt {:id :t-shirt :quantity 3 :price 40}
:shoes {:id :shoes :quantity 30}}})
(defn all-demands []
[demand, demand2, demand3, demand4, demand5])
handle.clj:
For import another file, just pass in your local namespace the keyword :require
to import for the standard definition namespace.file-name
, and if you want you can add an alias using :as
keyword, good pratices encourages us to follow same standard but abbreviated
(ns example.handle
:require '[example.db :as e.db])
(println (group-by :user (l.db/all-demands))) ;group all demands by user
;if you want count total per user you can do something like that:
(defn total-per-user [[user demands]]
{:user-id user
:total (count demands)})
(->> (l.db/all-demands)
(group-by :user)
(map total-per-user)
println)
Now you can "modularize" your Clojure project!
Top comments (0)