blob: 89dd660bc16491ca213b3cf07cdd5297f88a9c1b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
# frozen_string_literal: true
require "json-schema"
# 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
def initialize(options)
raise ArgumentError, "Expected 'filename' as an argument" unless options[:filename]
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
def valid_schema?(value)
JSON::Validator.validate(schema_path, value)
end
def schema_path
Rails.root.join('app', 'validators', 'json_schemas', "#{options[:filename]}.json").to_s
end
end
|