# Announcing bracket.cr - Safe Resource Management Pattern

**URL:** <https://forum.crystal-lang.org/t/announcing-bracket-cr-safe-resource-management-pattern/7786>\
**Category:** Community\
**Tags:** announces\
**Created:** [February 22, 2025, 8:16am UTC](https://forum.crystal-lang.org/t/announcing-bracket-cr-safe-resource-management-pattern/7786 "2025-02-22T08:16:15Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![wizzardx](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/wizzardx/32/2813_2.png) [@wizzardx](https://forum.crystal-lang.org/u/wizzardx)\
**Post date:** [February 22, 2025, 8:16am UTC](https://forum.crystal-lang.org/t/announcing-bracket-cr-safe-resource-management-pattern/7786/1 "2025-02-22T08:16:15Z")

</div>

Hello Crystal community!

I’m excited to share a new shard called `bracket` that implements the bracket pattern for safe resource management in Crystal. This pattern, similar to Python’s context managers or Haskell’s bracket pattern, ensures resources are properly initialized and cleaned up, even when exceptions occur.

## Basic Usage

```crystal
require "bracket"

# Simple example
setup = -> { "my resource" }
teardown = ->(resource : String) { puts "Cleaning up #{resource}"; nil }

Bracket.with_resource(setup, teardown) do |resource|
  puts "Using #{resource}"
end

```

## Features

- Guarantees resource cleanup even if exceptions occur
- Type-safe resource handling
- Simple, functional interface
- Works with any resource type

## Links

- GitHub: [GitHub - wizzardx/bracket: A Crystal shard implementing the bracket pattern for safe resource management. Ensures proper initialization and cleanup of resources, similar to Python's context managers or Haskell's bracket pattern.](https://github.com/wizzardx/bracket)
- Documentation: [Bracket - Safe Resource Management for Crystal](https://wizzardx.github.io/bracket/)

I’d love to hear your thoughts and feedback! If you find this useful or have suggestions for improvements, please let me know.

---

<div class="post-metadata">

**Author:** ![Blacksmoke16](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/blacksmoke16/32/1241_2.png) [@Blacksmoke16](https://forum.crystal-lang.org/u/Blacksmoke16)\
**Post date:** [February 22, 2025, 2:30pm UTC](https://forum.crystal-lang.org/t/announcing-bracket-cr-safe-resource-management-pattern/7786/2 "2025-02-22T14:30:17Z")

</div>

What benefits does this shard provide over just doing this?

```crystal
resource = "my resource"

begin
  puts "Using #{resource}"
ensure
  puts "Cleaning up #{resource}"
end

```

---

<div class="post-metadata">

**Author:** ![ComputerMage](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/computermage/32/719_2.png) [@ComputerMage](https://forum.crystal-lang.org/u/ComputerMage)\
**Post date:** [February 23, 2025, 12:48pm UTC](https://forum.crystal-lang.org/t/announcing-bracket-cr-safe-resource-management-pattern/7786/3 "2025-02-23T12:48:00Z")

</div>

Also, it can extend a little more in a Java way where if the class is extended from the Autoclosable interface, then it will be used under the hood in a try-with-resources pattern.

for such, some method **try(autoclosableInheritedObject, &block)** can be used where it will execute the block and then clear the resources.

I am not discouraging the topic starter from what he is doing, but just thinking of some more straightforward way.

---

<div class="post-metadata">

**Author:** ![wizzardx](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/wizzardx/32/2813_2.png) [@wizzardx](https://forum.crystal-lang.org/u/wizzardx)\
**Post date:** [February 23, 2025, 1:02pm UTC](https://forum.crystal-lang.org/t/announcing-bracket-cr-safe-resource-management-pattern/7786/4 "2025-02-23T13:02:20Z")

</div>

brackets are a design pattern. They aren’t very useful for simple cases like eg:

```auto
resource = "my resource"

begin
  puts "Using #{resource}"
ensure
  puts "Cleaning up #{resource}"
end

```

They tend to be more useful for say larger functions with resources of different types, that need to be opened/closed in specific sequence (eg mutexes, locks), and where you don’t want subtle bugs to be introduced later on by re-ordering code.

More info over here:

> **[Resource acquisition is initialization](https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization)**
>
> Resource acquisition is initialization (RAII) is a programming idiom used in several object-oriented, statically typed programming languages to describe a particular language behavior. In RAII, holding a resource is a class invariant, and is tied to object lifetime. Resource allocation (or acquisition) is done during object creation (specifically initialization), by the constructor, while resource deallocation (release) is done during object destruction (specifically finalization), by the RAII ...

---

<div class="post-metadata">

**Author:** ![wizzardx](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/wizzardx/32/2813_2.png) [@wizzardx](https://forum.crystal-lang.org/u/wizzardx)\
**Post date:** [February 23, 2025, 1:05pm UTC](https://forum.crystal-lang.org/t/announcing-bracket-cr-safe-resource-management-pattern/7786/5 "2025-02-23T13:05:35Z")

</div>

iirc in java it tends to be a bit more magic, where you’re not always 100% sure if a given class will or won’t autoclose itself?

Haviving a syntactic block structure , helps you to intuitively see the “liveliness” of various objects just by seeing the code on your screen, not by needing to go check the class definition.

---

<div class="post-metadata">

**Author:** ![straight-shoota](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/straight-shoota/32/36_2.png) [@straight-shoota](https://forum.crystal-lang.org/u/straight-shoota)\
**Post date:** [February 23, 2025, 2:43pm UTC](https://forum.crystal-lang.org/t/announcing-bracket-cr-safe-resource-management-pattern/7786/6 "2025-02-23T14:43:19Z")

</div>

> [@wizzardx](#):
>
> They tend to be more useful for say larger functions with resources of different types, that need to be opened/closed in specific sequence (eg mutexes, locks)

I can see that it might make sense to put the cleanup code closeby to the the setup code.  
I’m not convinced it is a good idea to use such a micro library for this when you can express the same in regular Crystal code. That’s more straightforward and easy to understand for anyone without being familiar with an external library (even though it’s very small).

In addition to [Announcing bracket.cr - Safe Resource Management Pattern - #2 by Blacksmoke16](https://forum.crystal-lang.org/t/announcing-bracket-cr-safe-resource-management-pattern/7786/2) you could also do something like this for explicitly placing the cleanup code next to the setup.

```cr
resource = "my resource"
teardown = ->(resource : String) { puts "Cleaning up #{resource}"; nil }

begin
  puts "Using #{resource}"
ensure
  teardown.call(resource)
end

```

Optionally extract `setup` into a proc as well, but for this example it seems unnecessary.

> [@wizzardx](#):
>
> you don’t want subtle bugs to be introduced later on by re-ordering code.

What kinds of bugs would that be though?  
The main factor I can think of is that the scope of `resource` is limited to the block, so you cannot use it outside of it.

There is actually a very similar idiom in Crystal (and Ruby) with yielding resources to a block. It combines the setup and teardown into an explicit method:

```cr
def with_resource
  resource = "my resource"
  begin
    yield resource
  ensure
    puts "Cleaning up #{resource}"
  end
end

with_resource do |resource|
  puts "Using #{resource}"
end

```

This is plain Crystal (or Ruby) so it’s very readable and the callsite is much cleaner than with that bracket call.  
IMO this is a stronger pattern and a better abstraction: Setup and teardown are syntactically merged in the same scope.  
Also, this trivially allows passing setup parameters. And it’s super composable:

```cr
with_resource do |resource|
  with_subresource(resource) do |subresource|
    puts "Using #{subresource}"
  end
end

```

---

<div class="post-metadata">

**Author:** ![wizzardx](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/wizzardx/32/2813_2.png) [@wizzardx](https://forum.crystal-lang.org/u/wizzardx)\
**Post date:** [February 24, 2025, 7:41am UTC](https://forum.crystal-lang.org/t/announcing-bracket-cr-safe-resource-management-pattern/7786/7 "2025-02-24T07:41:43Z")

</div>

You’re right to emphasize explicit control structures in Crystal, but what I’m doing with _bracket_ isn’t just syntactic sugar—it’s about _structured execution invariants_. The idea is to encode _delimited execution boundaries_ as a first-class abstraction, ensuring _correctness at the type level_ while preserving _functional-style encapsulation of resources_.

Think of it like Python’s `with`, but fully _type-checked_, _zero-cost_, and _extendable_ within Crystal’s existing semantics. The _core principle_ is enforcing _state transitions_ between acquisition, execution, and release in a way that allows _recursive execution contexts_ to be both safe and expressive.

_Crystal lacks a built-in bracketed execution pattern_, so this fills the gap by formalizing the invariant:

```crystal
bracket(acquire, release) do |resource|
  use(resource)
end

```

This isn’t just “another wrapper”—it _hardens_ execution flows by _guaranteeing finalization_ even in _nonlocal jumps, early returns, or failures_, while keeping it _idiomatic and efficient_.

Your concerns about explicitness make sense, but _bracket isn’t about hiding control flow_—it’s about _formalizing execution correctness_ at a fundamental level. If Crystal ever gets first-class linear types or effect tracking, this could integrate even deeper into the type system.

Would be interested in your take on _how we could extend this into structured concurrency patterns or effect handlers_—since that’s where this naturally scales next.
