Last active
June 21, 2016 09:12
Method missing in clojure
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
;;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