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)

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ JsonSchemaValidator

Returns a new instance of JsonSchemaValidator.

Raises:

  • (ArgumentError)

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

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)

  super(options)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object


23
24
25
26
27
# File 'app/validators/json_schema_validator.rb', line 23

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