64 lines
1.6 KiB
Markdown
64 lines
1.6 KiB
Markdown
# 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 then 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!
|