Class: Philiprehberger::TypedHash::Schema
- Inherits:
-
Object
- Object
- Philiprehberger::TypedHash::Schema
- Defined in:
- lib/philiprehberger/typed_hash/schema.rb
Overview
Schema definition for a typed hash
Instance Attribute Summary collapse
-
#fields ⇒ Hash
readonly
The field definitions.
-
#strict ⇒ Boolean
readonly
Whether unknown keys are rejected.
Instance Method Summary collapse
-
#from_json(json_str) ⇒ Instance
Deserialize a JSON string into a typed hash instance.
-
#initialize(strict: false) ⇒ Schema
constructor
A new instance of Schema.
-
#key(name, type, default: nil, optional: false, coerce: nil) ⇒ void
Define a key with a type and options.
-
#keys ⇒ Array<Symbol>
Return the declared top-level key names in definition order.
-
#nested(name, optional: false) {|schema| ... } ⇒ void
Define a nested typed hash schema.
-
#new(data = {}) ⇒ Instance
Create a new typed hash instance from data.
Constructor Details
#initialize(strict: false) ⇒ Schema
Returns a new instance of Schema.
8 9 10 11 |
# File 'lib/philiprehberger/typed_hash/schema.rb', line 8 def initialize(strict: false) @fields = {} @strict = strict end |
Instance Attribute Details
#fields ⇒ Hash (readonly)
Returns the field definitions.
17 18 19 |
# File 'lib/philiprehberger/typed_hash/schema.rb', line 17 def fields @fields end |
#strict ⇒ Boolean (readonly)
Returns whether unknown keys are rejected.
14 15 16 |
# File 'lib/philiprehberger/typed_hash/schema.rb', line 14 def strict @strict end |
Instance Method Details
#from_json(json_str) ⇒ Instance
Deserialize a JSON string into a typed hash instance
75 76 77 78 |
# File 'lib/philiprehberger/typed_hash/schema.rb', line 75 def from_json(json_str) data = JSON.parse(json_str, symbolize_names: true) new(data) end |
#key(name, type, default: nil, optional: false, coerce: nil) ⇒ void
This method returns an undefined value.
Define a key with a type and options
27 28 29 30 31 32 33 34 |
# File 'lib/philiprehberger/typed_hash/schema.rb', line 27 def key(name, type, default: nil, optional: false, coerce: nil) @fields[name] = { type: type, default: default, optional: optional, coerce: coerce } end |
#keys ⇒ Array<Symbol>
Return the declared top-level key names in definition order
Only returns top-level keys — nested schemas are represented by their parent key, not by their inner fields. The returned Array is a fresh copy; mutating it does not affect the schema.
59 60 61 |
# File 'lib/philiprehberger/typed_hash/schema.rb', line 59 def keys @fields.keys end |
#nested(name, optional: false) {|schema| ... } ⇒ void
This method returns an undefined value.
Define a nested typed hash schema
42 43 44 45 46 47 48 49 50 |
# File 'lib/philiprehberger/typed_hash/schema.rb', line 42 def nested(name, optional: false, &block) nested_schema = Schema.new(strict: @strict) nested_schema.instance_eval(&block) @fields[name] = { type: Hash, optional: optional, nested_schema: nested_schema } end |