The project is in a healthy, maintained state
Thread-local key-value state bag with scoped overrides via blocks, automatic restoration, and thread isolation for implicit context propagation.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies
 Project Readme

philiprehberger-state_bag

Tests Gem Version Last updated

Thread-local state bag for implicit context propagation

Requirements

  • Ruby >= 3.1

Installation

Add to your Gemfile:

gem "philiprehberger-state_bag"

Or install directly:

gem install philiprehberger-state_bag

Usage

require "philiprehberger/state_bag"

Philiprehberger::StateBag.set(:user_id, 42)
Philiprehberger::StateBag.get(:user_id)
# => 42

Default Values

Philiprehberger::StateBag.get(:missing, 'fallback')
# => "fallback"

Scoped Overrides

Philiprehberger::StateBag.set(:locale, 'en')

Philiprehberger::StateBag.with(locale: 'de') do
  Philiprehberger::StateBag.get(:locale)
  # => "de"
end

Philiprehberger::StateBag.get(:locale)
# => "en"

Fetch and Delete

require "philiprehberger/state_bag"

Philiprehberger::StateBag.set(:user, "Alice")
Philiprehberger::StateBag.fetch(:user)             # => "Alice"
Philiprehberger::StateBag.fetch(:missing, "default") # => "default"
Philiprehberger::StateBag.fetch(:missing) { |k| "no #{k}" } # => "no missing"

Philiprehberger::StateBag.delete(:user)  # => "Alice"
Philiprehberger::StateBag.key?(:user)    # => false

Inspection

Philiprehberger::StateBag.set(:a, 1)
Philiprehberger::StateBag.key?(:a)   # => true
Philiprehberger::StateBag.to_h       # => {:a=>1}
Philiprehberger::StateBag.clear

API

Method Description
.set(key, val) Store a value in the thread-local state bag
.get(key, default = nil) Retrieve a value or return the default
.with(**overrides, &block) Execute block with temporary state, restoring after
.fetch(key, default = UNSET, &block) Retrieve a value; raises KeyError if missing with no default/block
.delete(key) Remove a key and return its value
.clear Remove all entries from the state bag
.to_h Return a snapshot of the current state
.key?(key) Check if a key exists in the state bag

Development

bundle install
bundle exec rspec
bundle exec rubocop

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT