json_schemer
json_schemer copied to clipboard
Documentation
Improve the readme or introduce some other documentation.
@davishmcclurg, is it possible to use this in an Active Record model? Perhaps in the validates stage? I would like to use this as a replacement for this gem since the project (and its root dependency, the ruby json schema)seems to have stagnated.
@adityasrini there's no built-in way to generate active model validations, but a simple one using json-schemer should be fairly easy to rig up. The source for the gem you linked is helpful: https://github.com/mirego/activerecord_json_validator/blob/4b6ac6b9fe172de4ed36a83e19d6dbbc3f701c56/lib/active_record/json_validator/validator.rb#L14
I don't have any plans for built-in support.
Here's my custom validator:
app/validators/json_validator.rb
require 'json_schemer'
require 'pathname'
class JsonValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
schemer = load_schemer
return if schemer.valid?(value)
schemer.validate(value).each do |error|
record.errors[attribute] << error_message(error)
end
end
private
def load_schemer
path = Rails.root.join('app', 'validators', 'json_schemas', "#{options[:schema]}.json_schema").to_s
schema = Pathname.new(path)
JSONSchemer.schema(schema)
end
def error_message(error)
property_name = error['data_pointer'].blank? ? error['data'] : error['data_pointer']&.delete_prefix('/')
"#{property_name} is invalid"
end
end
Model
validates :some_json_field, json: { schema: 'some_json_field' }
Schema
app/validators/json_schemas/some_json_field.json_schema
For nice error messages you can use JSONSchemer::Errors.pretty(error)
Closing this because the readme covers most things now and I don't currently plan on introducing other documentation.