Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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