Schema is a project mainly written in Ruby, based on the MIT license.
Schemas for ruby hashes
Schema is a mechanism for enforcing schemas for ruby hashes. Type conversions are specified in a schema-hash and applied to a hash that shall be transformed.
Schema.transform({:float => '42', :array_of_strings => 23}, {:float => Float, :array_of_strings => [String]})
# => {:float => 42.0, :array_of_strings => ['23']}
or
Schema.include!
{:float => '42', :array_of_strings => 23}.transform({:float => Float, :array_of_strings => [String]})
# => {:float => 42.0, :array_of_strings => ['23']}
A Schema is either a type that implements #from
or a hash of schemas or an array with a schema as it's single element.
Float # is a schema
[Float] # is a schema
{ :string => String } # is a schema
{ :foo => [{ :bar => DateTime }]} # is a schema
Ruby has no Boolean class, therefore we define it, so we have:
"true".transform(Boolean) == true
nil is also a valid schema but it transforms everything to nil:
"string".transform(nil) == nil
In Hash-schemas keys may be optional indicated by a trailing question mark.
{ :optional => '42' }.transform({ :optional? => Float }) == { :optional => 42.0 }
{}.transform({ :optional? => Float }) == {}
This also enables circular schemas (for eg. trees)
schema = { :value => Float }
schema.update { :children? => [schema] }
Copyright (c) 2010 Daniel Kirsch. See LICENSE for details.