Sha256: 44630c9372c28725a969f38e6ce023c2ec07a9d180573ab21298fb6ee6584f24

Contents?: true

Size: 1.18 KB

Versions: 3

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true

module Grape
  module Exceptions
    class ValidationErrors < Grape::Exceptions::Base
      ERRORS_FORMAT_KEY = 'grape.errors.format'
      DEFAULT_ERRORS_FORMAT = '%<attributes>s %<message>s'

      include Enumerable

      attr_reader :errors

      def initialize(errors: [], headers: {}, **_options)
        @errors = errors.group_by(&:params)
        super(message: full_messages.join(', '), status: 400, headers: headers)
      end

      def each
        errors.each_pair do |attribute, errors|
          errors.each do |error|
            yield attribute, error
          end
        end
      end

      def as_json(**_opts)
        errors.map do |k, v|
          {
            params: k,
            messages: v.map(&:to_s)
          }
        end
      end

      def to_json(*_opts)
        as_json.to_json
      end

      def full_messages
        messages = map do |attributes, error|
          I18n.t(
            ERRORS_FORMAT_KEY,
            default: DEFAULT_ERRORS_FORMAT,
            attributes: translate_attributes(attributes),
            message: error.message
          )
        end
        messages.uniq!
        messages
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
grape-2.2.0 lib/grape/exceptions/validation_errors.rb
grape-2.1.3 lib/grape/exceptions/validation_errors.rb
grape-2.1.2 lib/grape/exceptions/validation_errors.rb