2020-05-29 17:08:35 -04:00
|
|
|
# frozen_string_literal: true
|
2020-05-30 02:08:31 -04:00
|
|
|
#
|
2020-05-29 17:08:35 -04:00
|
|
|
# JsonSchemaValidator
|
|
|
|
#
|
|
|
|
# Custom validator for json schema.
|
|
|
|
# Create a json schema within the json_schemas directory
|
|
|
|
#
|
|
|
|
# class Project < ActiveRecord::Base
|
|
|
|
# validates :data, json_schema: { filename: "file" }
|
|
|
|
# end
|
|
|
|
#
|
|
|
|
class JsonSchemaValidator < ActiveModel::EachValidator
|
2020-06-05 05:08:05 -04:00
|
|
|
FILENAME_ALLOWED = /\A[a-z0-9_-]*\Z/.freeze
|
|
|
|
FilenameError = Class.new(StandardError)
|
2021-03-16 05:11:17 -04:00
|
|
|
BASE_DIRECTORY = %w(app validators json_schemas).freeze
|
2020-06-05 05:08:05 -04:00
|
|
|
|
2020-05-29 17:08:35 -04:00
|
|
|
def initialize(options)
|
|
|
|
raise ArgumentError, "Expected 'filename' as an argument" unless options[:filename]
|
2020-06-05 05:08:05 -04:00
|
|
|
raise FilenameError, "Must be a valid 'filename'" unless options[:filename].match?(FILENAME_ALLOWED)
|
2020-05-29 17:08:35 -04:00
|
|
|
|
2021-03-16 05:11:17 -04:00
|
|
|
@base_directory = options.delete(:base_directory) || BASE_DIRECTORY
|
|
|
|
|
2020-05-29 17:08:35 -04:00
|
|
|
super(options)
|
|
|
|
end
|
|
|
|
|
|
|
|
def validate_each(record, attribute, value)
|
|
|
|
unless valid_schema?(value)
|
|
|
|
record.errors.add(attribute, "must be a valid json schema")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2021-03-16 05:11:17 -04:00
|
|
|
attr_reader :base_directory
|
|
|
|
|
2020-05-29 17:08:35 -04:00
|
|
|
def valid_schema?(value)
|
2021-03-23 14:09:05 -04:00
|
|
|
validator.valid?(value)
|
|
|
|
end
|
|
|
|
|
|
|
|
def validator
|
|
|
|
@validator ||= JSONSchemer.schema(Pathname.new(schema_path))
|
2020-05-29 17:08:35 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def schema_path
|
2021-03-16 05:11:17 -04:00
|
|
|
@schema_path ||= Rails.root.join(*base_directory, filename_with_extension).to_s
|
|
|
|
end
|
|
|
|
|
|
|
|
def filename_with_extension
|
|
|
|
"#{options[:filename]}.json"
|
2020-05-29 17:08:35 -04:00
|
|
|
end
|
2020-12-09 16:09:43 -05:00
|
|
|
|
|
|
|
def draft_version
|
|
|
|
options[:draft] || JSON_VALIDATOR_MAX_DRAFT_VERSION
|
|
|
|
end
|
2020-05-29 17:08:35 -04:00
|
|
|
end
|
2021-03-16 05:11:17 -04:00
|
|
|
|
2021-05-11 17:10:21 -04:00
|
|
|
JsonSchemaValidator.prepend_mod
|