class PactBroker::Api::Decorators::ValidationErrorsProblemJsonDecorator

Attributes

errors[R]

Public Class Methods

new(errors) click to toggle source

@param errors [Hash]

# File lib/pact_broker/api/decorators/validation_errors_problem_json_decorator.rb, line 12
def initialize(errors)
  @errors = errors
end

Public Instance Methods

to_hash(user_options:, **) click to toggle source

@return [Hash]

# File lib/pact_broker/api/decorators/validation_errors_problem_json_decorator.rb, line 17
def to_hash(user_options:, **)
  error_list = []
  walk_errors(errors, error_list, "", user_options[:base_url])
  {
    "title" => "Validation errors",
    "type" => "#{user_options[:base_url]}/problems/validation-error",
    "status" => 400,
    "instance" => "/",
    "errors" => error_list
  }
end
to_json(*args, **kwargs) click to toggle source

@return [String] JSON

# File lib/pact_broker/api/decorators/validation_errors_problem_json_decorator.rb, line 30
def to_json(*args, **kwargs)
  to_hash(*args, **kwargs).to_json
end

Private Instance Methods

append_error(list, message, path, base_url) click to toggle source
# File lib/pact_broker/api/decorators/validation_errors_problem_json_decorator.rb, line 52
def append_error(list, message, path, base_url)
  error = {
    "type" => "#{base_url}/problems/invalid-body-property-value",
    "title" => "Invalid body parameter",
    "detail" => message
  }
  error["pointer"] = path.tr(".", "/") if path.present?
  list << error
end
walk_errors(object, list, path, base_url) click to toggle source

The path is meant to be implemented using JSON Pointer, but this will probably do for now. As per gregsdennis.github.io/Manatee.Json/usage/pointer.html the only things that need to be escaped are “~” and “/”, which are unlikely to be used in a key name. You get what you deserve if you’ve done that.

# File lib/pact_broker/api/decorators/validation_errors_problem_json_decorator.rb, line 42
def walk_errors(object, list, path, base_url)
  if object.is_a?(Hash)
    object.each { | key, value | walk_errors(value, list, "#{path}/#{key}", base_url) }
  elsif object.is_a?(Array)
    object.each { | value | walk_errors(value, list, path, base_url) }
  elsif object.is_a?(String)
    append_error(list, object, path, base_url)
  end
end