philiprehberger-typed_hash
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_hashUsage
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? # => trueDefault 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? # => trueCoercion
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] # => 42Strict 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] # => 30API
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 rubocopSupport
If you find this project useful: