File: except_values.rb

package info (click to toggle)
ruby-grape 1.6.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,156 kB
  • sloc: ruby: 25,265; makefile: 7
file content (24 lines) | stat: -rw-r--r-- 818 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# frozen_string_literal: true

module Grape
  module Validations
    module Validators
      class ExceptValuesValidator < Base
        def initialize(attrs, options, required, scope, **opts)
          @except = options.is_a?(Hash) ? options[:value] : options
          super
        end

        def validate_param!(attr_name, params)
          return unless params.respond_to?(:key?) && params.key?(attr_name)

          excepts = @except.is_a?(Proc) ? @except.call : @except
          return if excepts.nil?

          param_array = params[attr_name].nil? ? [nil] : Array.wrap(params[attr_name])
          raise Grape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)], message: message(:except_values)) if param_array.any? { |param| excepts.include?(param) }
        end
      end
    end
  end
end