Class: Cocina::Models::Validators::JsonSchemaValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/cocina/models/validators/json_schema_validator.rb

Overview

Perform validation against JSON schema

Class Method Summary collapse

Class Method Details

.documentHash

Returns a hash representation of the schema.json document.

Returns:

  • (Hash)

    a hash representation of the schema.json document



22
23
24
25
26
27
# File 'lib/cocina/models/validators/json_schema_validator.rb', line 22

def self.document
  @document ||= begin
    file_content = ::File.read(schema_path)
    JSON.parse(file_content)
  end
end

.validate(clazz, attributes) ⇒ Object

Raises:



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/cocina/models/validators/json_schema_validator.rb', line 8

def self.validate(clazz, attributes)
  return unless clazz.name

  method_name = clazz.name.split('::').last

  attributes['cocinaVersion'] = Cocina::Models::VERSION if %w[DRO RequestDRO AdminPolicy RequestAdminPolicy Collection RequestCollection DROWithMetadata].include? method_name

  errors = schema.ref("#/$defs/#{method_name}").validate(attributes.as_json).to_a
  return unless errors.any?

  raise ValidationError, "When validating #{method_name}: " + errors.map { |e| e['error'] }.uniq.join(', ')
end