Class: Grape::Validations::Validators::OneofValidator
- 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
Instance Method Summary collapse
-
#initialize(attrs, options, required, scope, opts) ⇒ OneofValidator
constructor
A new instance of OneofValidator.
- #validate_param!(attr_name, params) ⇒ Object
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, , required, scope, opts) super @variants = Array() 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 |