Class: JsonSchemaValidator::JsonSchema

Inherits:
Base
  • Object
show all
Defined in:
lib/json_schema_validator/json-schema.rb

Instance Attribute Summary

Attributes inherited from Base

#files_to_validate

Instance Method Summary collapse

Methods inherited from Base

#errors, #log, #log_fmt, run, #success, #validate_all, #validate_data, #validate_schemas

Constructor Details

#initialize(files_to_validate) ⇒ JsonSchema

Returns a new instance of JsonSchema.



5
6
7
8
9
10
11
12
# File 'lib/json_schema_validator/json-schema.rb', line 5

def initialize(files_to_validate)
  @files_to_validate = files_to_validate
  @meta_schema_path  = "#{File.dirname(__FILE__)}/schema.json"

  # need to know the base dir of the schema to resolve relative uris.
  # see below.
  @schemadir = File.dirname(@files_to_validate[0])
end

Instance Method Details

#use_for_validation(schema) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/json_schema_validator/json-schema.rb', line 30

def use_for_validation(schema)
  schema_to_test = JSON.parse(schema)

  # json-schema resolves relatives path relative to it's own "."
  # not relative to the file containing the reference ...
  base_dir = Dir.pwd

  begin
    Dir.chdir @schemadir
    data = {}
    result = JSON::Validator.fully_validate(schema_to_test, data)
    if !result || result.length == 0
      success << schema_to_test['title']
    else
      errors << "Data validation failed: #{schema_to_test['title']}\n#{result.join("\n")}"
    end
  ensure
    Dir.chdir base_dir
  end
end

#validate(schema) ⇒ Object

Parameters:

  • schema (String)

    to test against the meta schema



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/json_schema_validator/json-schema.rb', line 15

def validate(schema)
  schema_to_test = JSON.parse(schema)
  begin
    result = JSON::Validator.fully_validate(@meta_schema_path, schema_to_test)
    if !result || result.length == 0
      success << schema_to_test['title'] || schema_to_test.keys[0]
    else
      errors << "Schema validation failed: #{schema_to_test['title']}\n#{result.join("\n")}"
    end
  rescue => e
    errors << "Schema validation failed: #{schema_to_test['title']}\n#{e}"
    # puts e.backtrace
  end
end