Created
June 23, 2010 01:53
-
-
Save qbg/449372 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| (ns destructors) | |
| (defprotocol Disposable | |
| (dispose [obj] "Dispose obj")) | |
| (declare *registered-objects*) | |
| (defn to-dispose | |
| [obj] | |
| (swap! *registered-objects* conj obj) | |
| obj) | |
| (defn cleanup | |
| [] | |
| (doseq [obj @*registered-objects*] | |
| (dispose obj))) | |
| (defmacro with-destructors | |
| [& body] | |
| `(binding [*registered-objects* (atom nil)] | |
| (try | |
| ~@body | |
| (finally (cleanup))))) | |
| (extend-type java.io.Closeable | |
| Disposable | |
| (dispose [obj] | |
| (.close obj))) | |
| ;;; Example usage | |
| (defn write-demo-file | |
| [string] | |
| (with-destructors | |
| (let [fw (to-dispose (java.io.FileWriter. "/tmp/test"))] | |
| (.write fw string 0 (count string))))) | |
| (defmacro my-with-open | |
| [bindings & body] | |
| (let [new-bindings (map #(if %1 %2 `(to-dispose ~%2)) | |
| (cycle [true false]) | |
| bindings)] | |
| `(with-destructors | |
| (let [~@new-bindings] | |
| ~@body)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment