context
Some resources, such as open files, have lifetimes which are better managed by the user than by the garbage collector. The context module provides a Context class that may be subclassed to assist in managing the lifetime of such resources.
Context
The Context class may be subclassed by a resource with a finite lifetime. Such
a resource may be passed to Context.with
, which will automatically call
close
on the subclass regardless of the outcome of the context function.
import "context" for Context
class MyResource is Context {
// ...
close() {
System.print("closed!")
}
}
Context.with(MyResource.open()) {|res|
res.do_work()
}
static with(res, fn)
Passes the given resource to the given function, then call res.close()
. The
resource will be closed regardless of the outcome of the function (e.g.
aborting with an error).