Class: Typed::Schema
- Inherits:
-
Object
- Object
- Typed::Schema
- Defined in:
- lib/typed/schema.rb
Constant Summary collapse
- NotFound =
Class.new(RuntimeError)
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, val) ⇒ Object
- #check!(key, val) ⇒ Object
- #exist?(key) ⇒ Boolean
-
#initialize(kvs) ⇒ Schema
constructor
A new instance of Schema.
Constructor Details
#initialize(kvs) ⇒ Schema
Returns a new instance of Schema.
5 6 7 8 |
# File 'lib/typed/schema.rb', line 5 def initialize(kvs) @kvs = kvs @types = {} end |
Instance Method Details
#[](key) ⇒ Object
14 15 16 |
# File 'lib/typed/schema.rb', line 14 def [](key) @types[key] end |
#[]=(key, val) ⇒ Object
18 19 20 21 22 23 24 25 |
# File 'lib/typed/schema.rb', line 18 def []=(key, val) # update schema if sub-class, otherwise raises val.must.struct(@types[key]) { raise TypeError, "%s is already typed as `%s'" % [key, @types[key].inspect] } if exist?(key) @types[key] = val end |
#check!(key, val) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/typed/schema.rb', line 27 def check!(key, val) struct = @types[key] or raise Schema::NotFound, key.to_s if val.must.struct?(struct) return true else expected = @types[key].inspect got = Must::StructInfo.new(val).compact.inspect value = val.inspect.truncate(200) raise TypeError, "%s(%s) got %s: %s" % [key, expected, got, value] end end |
#exist?(key) ⇒ Boolean
10 11 12 |
# File 'lib/typed/schema.rb', line 10 def exist?(key) @types.has_key?(key) end |