json_schemer icon indicating copy to clipboard operation
json_schemer copied to clipboard

Documentation

Open davishmcclurg opened this issue 6 years ago • 3 comments

Improve the readme or introduce some other documentation.

davishmcclurg avatar Mar 12 '19 06:03 davishmcclurg

@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 avatar Apr 04 '19 21:04 adityasrini

@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.

davishmcclurg avatar Apr 17 '19 05:04 davishmcclurg

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

Subtletree avatar Jun 17 '19 00:06 Subtletree

For nice error messages you can use JSONSchemer::Errors.pretty(error)

NeoPhi avatar Jul 13 '23 15:07 NeoPhi

Closing this because the readme covers most things now and I don't currently plan on introducing other documentation.

davishmcclurg avatar Nov 28 '23 16:11 davishmcclurg