Created
June 24, 2013 16:42
-
-
Save daveray/5851508 to your computer and use it in GitHub Desktop.
DI
This file contains 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 lookup | |
[dep-graph key] | |
(let [{:keys [deps fn]} (dep-graph key) | |
context (map (partial lookup dep-graph) deps) ] | |
(apply fn context))) | |
;############################################################################### | |
; Define some functions with deps encoded as metadata | |
(defn bar* | |
[a b] | |
(+ a b)) | |
(defn foo* | |
[bar x y] | |
(* (bar x y) (bar x y))) | |
(defn baz* | |
[foo bar pi a b] | |
(str "pi -> " pi ", (foo a b) -> " (foo a b) ", (bar a b) -> " (bar a b))) | |
;################################################################################ | |
; Map names to functions | |
(def deps {:bar {:deps [] | |
:fn (fn [] bar*)} | |
:foo {:deps [:bar] | |
:fn (fn [bar] (partial foo* bar))} | |
:pi {:deps [] :fn (constantly 3.14159)} | |
:baz {:deps [:foo :bar :pi] | |
:fn (fn [foo bar pi] (partial baz* foo bar pi))}}) | |
; Lookup and call a function | |
(let [baz (lookup deps :baz)] | |
(println (baz 1 2))) | |
;=> pi -> 3.14159 (foo a b) -> 9 , (bar a b) -> 3 | |
; Inject an alternate dependency impl, and call a function | |
(let [foo (lookup (assoc deps :bar {:deps [] :fn (constantly (constantly 100))}) | |
:foo)] | |
(println (foo 4 5))) | |
;=> 10000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment