Sha256: bff54c0832c4762c06421975ce94e60009c0cf663c4839122837676a5a695826

Contents?: true

Size: 1.33 KB

Versions: 14

Compression:

Stored size: 1.33 KB

Contents

require 'grape/exceptions/base'

module Grape
  module Exceptions
    class ValidationErrors < Grape::Exceptions::Base
      include Enumerable

      attr_reader :errors

      def initialize(errors: [], headers: {}, **_options)
        @errors = {}
        errors.each do |validation_error|
          @errors[validation_error.params] ||= []
          @errors[validation_error.params] << validation_error
        end

        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
        map { |attributes, error| full_message(attributes, error) }.uniq
      end

      private

      def full_message(attributes, error)
        I18n.t(
          'grape.errors.format'.to_sym,
          default: '%{attributes} %{message}',
          attributes: attributes.count == 1 ? translate_attribute(attributes.first) : translate_attributes(attributes),
          message: error.message
        )
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
grape-1.2.4 lib/grape/exceptions/validation_errors.rb
grape-1.2.3 lib/grape/exceptions/validation_errors.rb
grape-1.2.2 lib/grape/exceptions/validation_errors.rb
grape-1.2.1 lib/grape/exceptions/validation_errors.rb
grape-1.2.0 lib/grape/exceptions/validation_errors.rb
grape-1.1.0 lib/grape/exceptions/validation_errors.rb
grape-1.0.3 lib/grape/exceptions/validation_errors.rb
grape-1.0.2 lib/grape/exceptions/validation_errors.rb
grape-1.0.1 lib/grape/exceptions/validation_errors.rb
grape-1.0.0 lib/grape/exceptions/validation_errors.rb
grape-0.19.2 lib/grape/exceptions/validation_errors.rb
grape-0.19.1 lib/grape/exceptions/validation_errors.rb
grape-0.19.0 lib/grape/exceptions/validation_errors.rb
grape-0.18.0 lib/grape/exceptions/validation_errors.rb