The project is in a healthy, maintained state
Define typed hash schemas with per-key type declarations, optional coercion functions, default values, strict mode for unknown keys, and validation error collection.
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-typed_hash

Tests Gem Version Last updated

Hash with per-key type declarations, coercion, and validation

Requirements

  • Ruby >= 3.1

Installation

Add to your Gemfile:

gem "philiprehberger-typed_hash"

Or install directly:

gem install philiprehberger-typed_hash

Usage

require "philiprehberger/typed_hash"

UserSchema = Philiprehberger::TypedHash.define do
  key :name, String
  key :age, Integer
  key :email, String
end

user = UserSchema.new(name: 'Alice', age: 30, email: 'alice@example.com')
user[:name]   # => 'Alice'
user.valid?   # => true

Default Values

schema = Philiprehberger::TypedHash.define do
  key :name, String
  key :role, String, default: 'user'
end

instance = schema.new(name: 'Alice')
instance[:role]  # => 'user'

Optional Keys

schema = Philiprehberger::TypedHash.define do
  key :name, String
  key :nickname, String, optional: true
end

schema.new(name: 'Alice').valid?  # => true

Coercion

schema = Philiprehberger::TypedHash.define do
  key :count, Integer, coerce: ->(v) { Integer(v) }
  key :active, TrueClass, coerce: ->(v) { v == 'true' }
end

instance = schema.new(count: '42', active: 'true')
instance[:count]  # => 42

Strict Mode

schema = Philiprehberger::TypedHash.define(strict: true) do
  key :name, String
end

instance = schema.new(name: 'Alice', extra: 'value')
instance.valid?   # => false
instance.errors   # => ['unknown key: extra']

Merging

base = schema.new(name: 'Alice', age: 25)
updated = base.merge(age: 30)
updated[:age]  # => 30

API

TypedHash

Method Description
.define(strict:) { } Define a schema with a block DSL

Schema

Method Description
key :name, Type, opts Declare a typed key with options
#new(data) Create a typed hash instance

Instance

Method Description
#[key] Access a value by key
#valid? Check if the instance passes validation
#errors Return validation error messages
#to_h Convert to a plain hash
#merge(other) Merge with another hash or instance

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