Class: RubynCode::Config::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/rubyn_code/config/validator.rb

Constant Summary collapse

SCHEMA_PATH =
File.expand_path('schema.json', __dir__)

Instance Method Summary collapse

Constructor Details

#initializeValidator

Returns a new instance of Validator.



11
12
13
14
# File 'lib/rubyn_code/config/validator.rb', line 11

def initialize
  @raw_schema = JSON.parse(File.read(SCHEMA_PATH))
  @schemer = JSONSchemer.schema(@raw_schema)
end

Instance Method Details

#validate(key, value) ⇒ Hash

Validates a single config key/value pair against the schema.

Parameters:

  • key (String)

    the config key

  • value (Object)

    the value to validate

Returns:

  • (Hash)

    { valid: true/false, errors: [String] }



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rubyn_code/config/validator.rb', line 21

def validate(key, value)
  # If the key has no schema definition, accept any value
  properties = @raw_schema.fetch('properties', {})
  unless properties.key?(key.to_s)
    return { valid: true, errors: [] }
  end

  doc = { key.to_s => value }
  errors = @schemer.validate(doc).select { |e| e['data_pointer'] == "/#{key}" }

  if errors.empty?
    { valid: true, errors: [] }
  else
    messages = errors.map { |e| format_error(key, e) }
    { valid: false, errors: messages }
  end
end