class HecksPlugins::JSONValidator

A validator that is built on top of json-schema to provide more functionality than the basic hecks validator. Builds a json schema from a head spec and validates the user's input against it.

Constants

MATCHERS

These matchers create a cleaner, more user-friendly message out of the messages returned by json-schema

Attributes

args[R]
domain_module[R]
errors[R]
schema[R]
schema_parser[R]
validator[R]

Public Class Methods

new(command:) click to toggle source
# File lib/hecks-plugins-json-validator.rb, line 13
def initialize(command:)
  @args          = command.args
  @domain_module = command.domain_module
  @errors        = {}
  @schema_parser = SchemaParser.new(
    domain_module: domain_module,
    object:        command.domain_module.head
  ).call

  @validator     = JSON::Validator
end

Public Instance Methods

call() click to toggle source
# File lib/hecks-plugins-json-validator.rb, line 25
def call
  parse_schema
  validate
  self
end

Private Instance Methods

parse_schema() click to toggle source
# File lib/hecks-plugins-json-validator.rb, line 35
def parse_schema
  @schema = schema_parser.schema
end
validate() click to toggle source
# File lib/hecks-plugins-json-validator.rb, line 39
def validate
  MATCHERS.each do |matcher|
    result = validator.fully_validate(schema, args, errors_as_objects: true)

    result.each do |error|
      parser = MessageParser.new(matcher: matcher, error: error).call
      next unless parser.message
      if parser.fragment && parser.fragment != parser.field_name
        errors[parser.fragment] ||= {}
        errors[parser.fragment][parser.field_name] ||= []
        errors[parser.fragment][parser.field_name] << parser.message
      else
        errors[parser.field_name] ||= []
        errors[parser.field_name] << parser.message
      end
    end
  end
end