bracket

Version, currently 0.1.01 version
  • 0.1.0latestFeb 22, 2025

github.com/wizzardx/bracket

Safe resource management for Crystal using the bracket pattern

1 stars
0 dependents
License: MIT

Installation

# Add this to your shard.yml
dependencies:
  bracket:
    github: wizzardx/bracket
    version: ~> 0.1.0

Then run:

shards install

shard.yml

Crystal
>= 1.15.1
License
MIT
Author
david

Dependencies

This version declares no dependencies.

README

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

  1. Add the dependency to your shard.yml:

    dependencies:
      bracket:
        github: wizzardx/bracket
  2. 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

  1. Fork it (https://github.com/wizzardx/bracket/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors