Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@killme2008
Last active June 21, 2016 09:12
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 killme2008/213c9d35af50ad49d9483b7e2029d385 to your computer and use it in GitHub Desktop.
Save killme2008/213c9d35af50ad49d9483b7e2029d385 to your computer and use it in GitHub Desktop.
Method missing in clojure
;;namespace test
(ns missing-test)
(defn method-missing [func args]
(println "missing '" func "' with args:" args)
[func args])
(defn hello [name]
(str "hello," name))
;;example namesapce
(ns missing-example
(:require [missing-test :as t]))
(defn- this-ns? [ns f]
(try
(let [n (str f)]
(when (.contains n "/")
(let [nsm (-> n (.split "/") first symbol)]
(= ns (get (ns-aliases *ns*)
nsm)))))
(catch Exception e
false)))
(defn- method-missing? [ns f]
(try
(and (nil? (resolve f))
(get (ns-publics ns)
'method-missing))
(catch Exception e
false)))
(defmacro with-method-missing [ns & body]
(let [ns (eval ns)]
`(do
~@(clojure.walk/postwalk
(fn [form]
(if (and (list? form)
(this-ns? ns (first form))
(method-missing? ns (first form)))
(list `apply (get (ns-publics ns)
'method-missing)
(vec (cons
(name (first form))
(next form))))
form))
body))))
;;invoke with method missing
(with-method-missing (the-ns 'missing-test)
(println (t/hello "dennis"))
(println (t/world "dennis")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment