github.com/wizzardx/bracket
0.1.0 / published Feb 22, 2025 / repository
Safe resource management for Crystal using the bracket pattern
bracket
A Crystal shard that implements the bracket pattern for safe resource management. This pattern, similar to Python's context managers, Rust's RAII, or Haskell's bracket pattern, ensures that resources are properly initialized and cleaned up even when exceptions occur. Useful for managing file handles, network connections, database transactions, or any resource that needs guaranteed cleanup.
Installation
-
Add the dependency to your
shard.yml:dependencies: bracket: github: wizzardx/bracket -
Run
shards install
Usage
require "bracket"
# Simple example with a string resource
setup = -> { "my resource" }
teardown = ->(resource : String) { puts "Cleaning up #{resource}"; nil }
Bracket.with_resource(setup, teardown) do |resource|
puts "Using #{resource}"
end
# Example with server resource
server_setup = -> {
port = find_available_port
server = start_server(port)
{server, port}
}
server_teardown = ->(resource : Tuple(Server, Int32)) {
server, port = resource
server.stop
nil
}
Bracket.with_resource(server_setup, server_teardown) do |resource|
server, port = resource
# Use server...
end
Features
- Guarantees resource cleanup even if an exception occurs
- Type-safe resource handling
- Simple, functional interface
- Works with any resource type
Development
Run tests:
crystal spec
Contributing
- Fork it (https://github.com/wizzardx/bracket/fork)
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request
Contributors
- David Purdy - creator and maintainer
API
- Bracket
Implements the bracket pattern for safe resource management in Crystal.