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: nil, hints: nil, base_error: nil, form_errors: false) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/salestation/web/responses.rb', line 69

def self.create(errors: nil, hints: nil, base_error: nil, form_errors: false)
  message = errors ? parse_errors(errors) : nil
  debug_message = hints ? parse_hints(hints) : nil

  UnprocessableEntity.new(
    message: message,
    debug_message: debug_message,
    form_errors: form_errors ? errors : nil,
    base_error: base_error
  )
end

.parse_errors(errors) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/salestation/web/responses.rb', line 81

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



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/salestation/web/responses.rb', line 96

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