Class: Grape::Validations::Validators::OneofValidator

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

Overview

Validates that a Hash parameter matches at least one of a set of variant schemas. Each variant is a list of pre-built validators captured by evaluating the variant’s block in a OneofCollector-backed ParamsScope. At request time we try each variant in order against a deep-dup of the value; the first variant that produces no errors wins and its (possibly coerced) hash replaces the original.

Instance Attribute Summary

Attributes inherited from Base

#attrs

Instance Method Summary collapse

Methods inherited from Base

default_message_key, inherited, new, #validate, #validate!

Constructor Details

#initialize(attrs, options, required, scope, opts) ⇒ OneofValidator

Returns a new instance of OneofValidator.



15
16
17
18
# File 'lib/grape/validations/validators/oneof_validator.rb', line 15

def initialize(attrs, options, required, scope, opts)
  super
  @variants = Array(options)
end

Instance Method Details

#validate_param!(attr_name, params) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/grape/validations/validators/oneof_validator.rb', line 20

def validate_param!(attr_name, params)
  value = params[attr_name]
  return if value.nil? && !required?

  winning_candidate = nil
  @variants.each do |variant_validators|
    candidate = value.deep_dup
    if variant_matches?(variant_validators, candidate)
      winning_candidate = candidate
      break
    end
  end

  return params[attr_name] = winning_candidate if winning_candidate

  validation_error!(attr_name)
end