Module: PactBroker::Api::Contracts::DryValidationErrorsFormatter

Extended by:
DryValidationErrorsFormatter
Included in:
BaseContract, DryValidationErrorsFormatter
Defined in:
lib/pact_broker/api/contracts/dry_validation_errors_formatter.rb

Instance Method Summary collapse

Instance Method Details

#add_error(errors_hash, key, text) ⇒ Object



32
33
34
35
# File 'lib/pact_broker/api/contracts/dry_validation_errors_formatter.rb', line 32

def add_error(errors_hash, key, text)
  errors_hash[key] ||= []
  errors_hash[key] << text
end

#add_indexed_error(errors_hash, error) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/pact_broker/api/contracts/dry_validation_errors_formatter.rb', line 38

def add_indexed_error(errors_hash, error)
  error_path_classes = error.path.collect(&:class)
  if error_path_classes == [Symbol, Integer, Symbol]
    add_error(errors_hash, error.path.first, "#{error.path.last} #{error.text} (at index #{error.path[1]})")
  elsif error_path_classes == [Symbol, Integer]
    add_error(errors_hash, error.path.first, "#{error.text} (at index #{error.path[1]})")
  else
    # Don't have any usecases for this - will deal with it when it happens
    raise PactBroker::Error, "Cannot currently format an error message with path classes #{error_path_classes}"
  end
end

#format_errors(errors) ⇒ Hash

Formats the dry validation errors in the expected PactBroker error format of { :key => [“errors”] } where there are no nested hashes.

Parameters:

  • errors (Dry::Validation::MessageSet)

Returns:

  • (Hash)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/pact_broker/api/contracts/dry_validation_errors_formatter.rb', line 14

def format_errors(errors)
  errors.each_with_object({}) do | error, errors_hash |
    integers = error.path.select{ | k | k.is_a?(Integer) }

    if integers.size > 1
      raise PactBroker::Error,  "Cannot currently format an error message with more than one index"
    end

    if integers.empty?
      key = error.path == [nil] ? nil : error.path.join(".").to_sym
      add_error(errors_hash, key, error.text)
    else
      add_indexed_error(errors_hash, error)
    end
  end
end