Skip to content

Instantly share code, notes, and snippets.

@daveray
Created June 14, 2013 04:40
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 daveray/5779503 to your computer and use it in GitHub Desktop.
Save daveray/5779503 to your computer and use it in GitHub Desktop.
Simple DI
(defn lookup
[dep-graph key]
(let [var (get dep-graph key)
context (->> (for [d (-> var meta :deps)]
[d (lookup dep-graph d)])
(into {}))]
(partial var context)))
;###############################################################################
; Define some functions with deps encoded as metadata
(defn bar*
[_ a b]
(+ a b))
(defn foo*
{:deps [:bar]}
[{:keys [bar]} x y]
(* (bar x y) (bar x y)))
(defn baz*
{:deps [:foo :bar :pi]}
[{:keys [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 #'bar*
:foo #'foo*
:pi (constantly 3.14159)
:baz #'baz* })
; 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 (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