Class: Edoxen::SchemaValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/edoxen/schema_validator.rb,
sig/edoxen.rbs

Overview

Services.

Defined Under Namespace

Modules: LineMap

Constant Summary collapse

ValidationError =

Back-compat alias. The canonical type is Edoxen::ValidationError; this constant lets existing callers keep writing SchemaValidator::ValidationError after the unification.

Returns:

Edoxen::ValidationError

Instance Method Summary collapse

Constructor Details

#initialize(schema_path = default_schema_path) ⇒ SchemaValidator

Returns a new instance of SchemaValidator.

Parameters:

  • schema_path (String) (defaults to: default_schema_path)


29
30
31
32
# File 'lib/edoxen/schema_validator.rb', line 29

def initialize(schema_path = default_schema_path)
  @schema_path = schema_path
  @schemer = load_schemer(schema_path)
end

Instance Method Details

#validate_content(content, file_path) ⇒ Array[Edoxen::ValidationError]

Validate a YAML string. Returns an array of Edoxen::ValidationError.

Parameters:

  • content (String)
  • file_path (String)

Returns:



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/edoxen/schema_validator.rb', line 46

def validate_content(content, file_path)
  data = normalize_dates(YAML.safe_load(content, permitted_classes: [Date, Time]))
  line_map = LineMap.build(content)

  @schemer.validate(data).to_a.map do |err|
    pointer = err.fetch("data_pointer", "")
    message = format_message(err)
    line, column = LineMap.locate(pointer, line_map)
    ValidationError.new(
      file: file_path, line: line, column: column,
      message_text: message, pointer: pointer,
      source: Edoxen::ValidationError::SOURCE_SCHEMA
    )
  end
rescue Psych::SyntaxError => e
  [ValidationError.new(
    file: file_path, line: e.line || 1, column: e.column || 1,
    message_text: "YAML syntax error: #{e.problem}",
    source: Edoxen::ValidationError::SOURCE_SYNTAX
  )]
end

#validate_file(file_path) ⇒ Array[Edoxen::ValidationError]

Validate a YAML file. Returns an array of Edoxen::ValidationError (empty = ok).

Parameters:

  • file_path (String)

Returns:



36
37
38
39
40
41
42
43
# File 'lib/edoxen/schema_validator.rb', line 36

def validate_file(file_path)
  validate_content(File.read(file_path), file_path)
rescue Errno::ENOENT
  [ValidationError.new(
    file: file_path, line: 1, column: 1,
    message_text: "File not found", source: Edoxen::ValidationError::SOURCE_SCHEMA
  )]
end