Skip to content

Commit

Permalink
Add load-hierarchy function
Browse files Browse the repository at this point in the history
Allows keyword hierarchy to be discoverable.
  • Loading branch information
weavejester committed Sep 7, 2023
1 parent d6b5b4c commit b0ba20d
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/integrant/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,34 @@
(distinct)
(keep try-require))))))

#?(:clj
(defn- resources [path]
(let [cl (.. Thread currentThread getContextClassLoader)]
(enumeration-seq (.getResources cl path)))))

#?(:clj
(defn load-hierarchy
"Search the base classpath for all resources that share the same
path (by default `integrant/hierarchy.edn`), and use their contents
to extend the global `derive` hierarchy. This allows a hierarchy to be
constructed without needing to load every namespace.
The hierarchy resources should be edn files that map child keywords
to vectors of parents. For example:
{:example/child [:example/father :example/mother]}
This is equivalent:
(derive :example/child :example/father)
(derive :example/child :example/mother)"
([] (load-hierarchy "integrant/hierarchy.edn"))
([path]
(doseq [url (resources path)]
(let [hierarchy (edn/read-string (slurp url))]
(doseq [[tag parents] hierarchy, parent parents]
(derive tag parent)))))))

(defn- missing-refs-exception [config refs]
(ex-info (str "Missing definitions for refs: " (str/join ", " refs))
{:reason ::missing-refs
Expand Down
10 changes: 10 additions & 0 deletions test/integrant/core_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,16 @@

(derive :integrant.test-child/foo :integrant.test/foo)

#?(:clj
(deftest load-hierarchy-test
(try
(ig/load-hierarchy)
(is (isa? :example/child :example/father))
(is (isa? :example/child :example/mother))
(finally
(underive :example/child :example/father)
(underive :example/child :example/mother)))))

#?(:clj
(deftest load-namespaces-test
(testing "all namespaces"
Expand Down
1 change: 1 addition & 0 deletions test/integrant/hierarchy.edn
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{:example/child [:example/father :example/mother]}

0 comments on commit b0ba20d

Please sign in to comment.