Class: Grape::Validations::ValuesValidator

Inherits:
Base
  • Object
show all
Defined in:
lib/grape/validations/validators/values.rb

Instance Attribute Summary

Attributes inherited from Base

#attrs

Instance Method Summary collapse

Methods inherited from Base

convert_to_short_name, #fail_fast?, inherited, #message, #options_key?, #validate, #validate!

Constructor Details

#initialize(attrs, options, required, scope, opts = {}) ⇒ ValuesValidator

Returns a new instance of ValuesValidator.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/grape/validations/validators/values.rb', line 4

def initialize(attrs, options, required, scope, opts = {})
  if options.is_a?(Hash)
    @excepts = options[:except]
    @values = options[:value]
    @proc = options[:proc]

    warn '[DEPRECATION] The values validator except option is deprecated. ' \
         'Use the except validator instead.' if @excepts

    raise ArgumentError, 'proc must be a Proc' if @proc && !@proc.is_a?(Proc)
    warn '[DEPRECATION] The values validator proc option is deprecated. ' \
         'The lambda expression can now be assigned directly to values.' if @proc
  else
    @excepts = nil
    @values = nil
    @proc = nil
    @values = options
  end
  super
end

Instance Method Details

#validate_param!(attr_name, params) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/grape/validations/validators/values.rb', line 25

def validate_param!(attr_name, params)
  return unless params.is_a?(Hash)
  return unless params[attr_name] || required_for_root_scope?

  param_array = params[attr_name].nil? ? [nil] : Array.wrap(params[attr_name])

  raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: except_message \
    unless check_excepts(param_array)

  raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: message(:values) \
    unless check_values(param_array, attr_name)

  raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: message(:values) \
    if @proc && !param_array.all? { |param| @proc.call(param) }
end