Skip to content

Instantly share code, notes, and snippets.

@qbg
Created June 23, 2010 01:53
Show Gist options
  • Save qbg/449372 to your computer and use it in GitHub Desktop.
Save qbg/449372 to your computer and use it in GitHub Desktop.
(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