This commit is contained in:
hellerve
2016-09-12 17:56:36 +02:00
commit b809a26bb4
3 changed files with 96 additions and 0 deletions

63
README.md Normal file
View File

@@ -0,0 +1,63 @@
# context
A context manager protocol for zepto.
## Installation
```
zeps install hellerve/context
```
## Context Managers?
Context managers provide the programmer with an easy way
to work with resources that need management, i.e. explicit
cleanup and/or deletion. Consider files for example: if
we want to use them, we need to open them, work with them
and the close them again. Context managers provide you with
a context in which a file will be open, managing the closing
itself when you are done.
An example:
```clojure
; reading the first line of a file, without a context manager
(define file (open-input-file "myfile.txt"))
(write (read-line file))
(close-input-file file)
; the same, this time with a context manager
(with (open-input-file "myfile.txt") file
(write (read-line file)))
```
## Usage
The example above already showcases the most important function for
users, `with`. It takes a value, a name to bind it to and a context
in which this name should be defined.
```clojure
(with some-resource some-name
(do-something some-name)
(do-another-thing some-name))
```
The library also exposes a protocol `context-manager`, comprised of a
function `teardown` which will clean a resource up after use.
Use it like so:
````clojure
(defimpl context-manager my-resource?
((teardown (lambda (resource)
(begin
(cleanup-my-resource resource)
(delete-my-resource resource))))))
```
That's all, folks!
This library comes bundled with a context manager for files and sockets.
<hr/>
Have fun!

21
context.zp Normal file
View File

@@ -0,0 +1,21 @@
(define-syntax with
(syntax-rules
"use a context manager. Takes a value, name and body
and binds value to name in body. Ensures resource cleanup.
params:
- val: the value to bind
- var: the name to bind to
- body: varargs for the body
complexity: O(1)
returns: the result of the resource cleanup"()
((_ val var body ...)
(let ((var val))
(begin
body ...
(teardown var))))))
(defprotocol context-manager ((teardown 1)))
(defimpl context-manager input-port? ((teardown close-input-file)))
(defimpl context-manager output-port? ((teardown close-output-file)))
(defimpl context-manager net:socket? ((teardown net:close-socket)))

12
module.zp Normal file
View File

@@ -0,0 +1,12 @@
#{:name "context"
:version "0.0.1"
:license "GPLv2"
:type :library
:tests []
:author #{:name "Veit Heller"
:email "veit@veitheller.de"
:github "@hellerve"}
:zepto #{:version "0.9.6"}
:dependencies ()
:dev-dependencies ()}