GitXplorerGitXplorer
i

json_validator

public
9 stars
0 forks
1 issues

Commits

List of commits on branch master.
Unverified
1b1d148764ecf952e998538659b1bb7c39df88e1

Updated code climate badge

iiainbeeston committed 5 years ago
Unverified
94805199c9ee5f0dea7cb30e3a528aa4a3a76127

Merge pull request #1 from iainbeeston/update-travis-build

iiainbeeston committed 10 years ago
Unverified
73ae16b3e263e1cb8234ce15ecf8de6d12051120

Made sure we test against the latest version of rubinius

iiainbeeston committed 10 years ago
Unverified
d3657c010c0c659d6b6c0bd596cfe653af058173

Added ruby 2.2 to the build matrix

iiainbeeston committed 10 years ago
Unverified
c1379b76190a53546a074643f9db8b1aaaa58eed

Added rails 4.2 to the build matrix

iiainbeeston committed 10 years ago
Unverified
6936586a021b83e0237b7c215f89f4facee79d9f

Added a test for valid models

iiainbeeston committed 10 years ago

README

The README file for this repository.

JsonValidator

Gem Version Build Status Code Climate

JsonValidator is an ActiveModel validator that validates any hash field against JSONSchema, returning errors in the model's own errors attribute.

This gem was originally written to provide deep validation of JSON attributes, which are available alongside primative types in recent versions of PostgreSQL, but it works equally well with ActiveModel objects.

Most of the functionality is dependent on the wonderful json-schema gem.

Usage

If you're using Ruby on Rails and ActiveRecord, add a validation to your model like this:

class Foo < ActiveRecord::Base
  validates :bar, json: {
    schema: JSON.parse(File.read('foo_schema.json'))
  }
end

And you have a schema file (ie. foo_schema.json) like this:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Universal spoons schema",
    "properties": {
      "handleSize": {
      "type": "integer",
      "minimum": 0
    }
  },
  "required": ["handleSize"]
}

Then whenever an instance of Foo is saved, Foo.bar (assumed to be a hash) will be validated against the JSON schema specified. So, for example:

f = Foo.new(bar: { handleSize: -10 })
f.valid? # false
f.errors.full_messages # ["Bar is invalid (the property '#/handleSize' did not have a minimum value of 0, inclusively)"]

The attribute being validated can be either a hash or a string (which will be parsed as JSON). The schema can be either a hash or a Proc that returns a hash (if you'd like to decide on the schema at runtime), and there's no reason why you could not load your schema from a .json file.