Class: Salestation::Web::Responses::UnprocessableEntityFromSchemaErrors

Inherits:
Object
  • Object
show all
Defined in:
lib/salestation/web/responses.rb

Class Method Summary collapse

Class Method Details

.create(errors:, hints:) ⇒ Object



49
50
51
52
53
54
# File 'lib/salestation/web/responses.rb', line 49

def self.create(errors:, hints:)
  message = parse_errors(errors)
  debug_message = parse_hints(hints)

  UnprocessableEntity.new(message: message, debug_message: debug_message)
end

.parse_errors(errors) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/salestation/web/responses.rb', line 56

def self.parse_errors(errors)
  parsed_errors = errors.map do |field, error_messages|
    if error_messages.is_a?(Hash)
      errors_with_nested_keys = error_messages.keys.map do |key|
        { "#{field}.#{key}" => error_messages[key] }
      end

      parse_errors(errors_with_nested_keys.reduce(Hash.new, :merge))
    else
      "'#{field}' #{error_messages.join(' and ')}"
    end
  end
  parsed_errors.join(". ")
end

.parse_hints(hints) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/salestation/web/responses.rb', line 71

def self.parse_hints(hints)
  parsed_hints = hints.select { |field, hint_messages| hint_messages.any? }
    .map do |field, hint_messages|
      if hint_messages.is_a?(Hash)
        hints_with_nested_keys = hint_messages.keys.map do |key|
          { "#{field}.#{key}" => hint_messages[key] }
        end

        parse_hints(hints_with_nested_keys.reduce(Hash.new, :merge))
      else
        "'#{field}' #{hint_messages.join(' and ')}"
      end
    end
  parsed_hints.join(". ")
end