Class: JsonSchemaValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/json_schema_validator.rb

Overview

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

Constant Summary collapse

FILENAME_ALLOWED =
/\A[a-z0-9_-]*\Z/.freeze
FilenameError =
Class.new(StandardError)
BASE_DIRECTORY =
%w(app validators json_schemas).freeze

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ JsonSchemaValidator

Returns a new instance of JsonSchemaValidator.

Raises:

  • (ArgumentError)

17
18
19
20
21
22
23
24
# File 'app/validators/json_schema_validator.rb', line 17

def initialize(options)
  raise ArgumentError, "Expected 'filename' as an argument" unless options[:filename]
  raise FilenameError, "Must be a valid 'filename'" unless options[:filename].match?(FILENAME_ALLOWED)

  @base_directory = options.delete(:base_directory) || BASE_DIRECTORY

  super(options)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object


26
27
28
29
30
31
32
# File 'app/validators/json_schema_validator.rb', line 26

def validate_each(record, attribute, value)
  value = value.to_h.stringify_keys if options[:hash_conversion] == true

  unless valid_schema?(value)
    record.errors.add(attribute, _("must be a valid json schema"))
  end
end