Build JSON Schemas with Ruby. Validates JSON using json-schema
Add this line to your application's Gemfile:
gem'json-schema_builder'And then execute:
$ bundle
Or install it yourself as:
$ gem install json-schema_builder
require'json/schema_builder'classYourSchemaincludeJSON::SchemaBuilderdefschemaobjectdostring:name,min_length: 1,required: truearray:your_idsdomax_items10unique_itemstrueitemstype: :integerendendendendbuilder=YourSchema.newbuilder.schema.as_json will return a valid JSON schema:
{
"type": "object",
"required": "name",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"your_ids": {
"type": "array",
"maxItems": 10,
"uniqueItems": true,
"items": { "type": "integer" }
}
}
}More examples can be found in the specs.
builder.schema.validate(data) will validate your object against the schema:
builder.schema.validate({})# => falsebuilder.schema.validatename: 'Your Name'# => truebuilder.schema.validate!(data) validates your object, raising an exception on failure:
builder.schema.validate!({})# JSON::Schema::ValidationError: The property '#/' did not contain a required property of 'name'builder.schema.validate!name: 'Your Name',your_ids: [1,1,2]# JSON::Schema::ValidationError: The property '#/your_ids' contained duplicated array valuesbuilder.schema.fully_validate(data) validates the object and reports all invalid properties:
builder.schema.fully_validateyour_ids: 'fail'# [# "The property '#/your_ids' of type String did not match the following type: array ",# "The property '#/' did not contain a required property of 'name'"# ]Fragment validation can be accomplished by specifying the schema fragment:
builder.schema.validate[1],fragment: '#/properties/your_ids'# => truejson-schema validation options can be specified in several contexts:
# As a global defaultJSON::SchemaBuilder.configuredo |opts|
opts.validate_schema=trueend# As a class-level defaultYourSchema.configuredo |opts|
opts.insert_defaults=trueend# Or at validationbuilder.schema.validatedata,strict: true,validate_schema: false# Results in{validate_schema: false,insert_defaults: true,strict: true}- Fork it ( https://github.com/parrish/json-schema_builder/fork )
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request