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", size_limit: 64.kilobytes }
end

Constant Summary collapse

FILENAME_ALLOWED =
/\A[a-z0-9_-]*\Z/
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)


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

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
  @size_limit = options.delete(:size_limit)

  super(options)
end

Instance Method Details

#schemaObject



47
48
49
# File 'app/validators/json_schema_validator.rb', line 47

def schema
  @schema ||= JSONSchemer.schema(schema_path)
end

#validate_each(record, attribute, value) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/validators/json_schema_validator.rb', line 28

def validate_each(record, attribute, value)
  value = Gitlab::Json.parse(Gitlab::Json.dump(value)) if options[:hash_conversion] == true
  value = Gitlab::Json.parse(value.to_s) if options[:parse_json] == true && !value.nil?

  if size_limit && !valid_size?(value)
    record.errors.add(attribute, size_error_message)
    return
  end

  if options[:detail_errors]
    schema.validate(value).each do |error|
      message = format_error_message(error)
      record.errors.add(attribute, message)
    end
  else
    record.errors.add(attribute, error_message) unless valid_schema?(value)
  end
end