Class: Axn::Validators::ShapeValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- Axn::Validators::ShapeValidator
- Defined in:
- lib/axn/core/validation/validators/shape_validator.rb
Overview
Validates the per-member shape of a structured field declared via a block:
expects :items, type: Array do
field :status, type: String, inclusion: { in: %w[a b] }
end
options is an array of ShapeConfig-like objects (responding to #field and #validations); options is the declared structured type (Array, Hash, or a class). For an Array container each element is validated with its index in the message; for any other container the single value’s members are validated directly. A value that doesn’t match the declared container is left to TypeValidator (we don’t try to extract members from it). Nesting falls out for free: a member whose validations include a :shape key recurses through the same machinery.
Instance Method Summary collapse
Instance Method Details
#check_validity! ⇒ Object
21 22 23 |
# File 'lib/axn/core/validation/validators/shape_validator.rb', line 21 def check_validity! raise ArgumentError, "must supply :members" if [:members].nil? end |
#validate_each(record, attribute, value) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/axn/core/validation/validators/shape_validator.rb', line 25 def validate_each(record, attribute, value) return if value.nil? && ([:allow_nil] || [:allow_blank]) if [:container] == Array return unless value.is_a?(Array) # TypeValidator owns the non-Array error value.each_with_index do |element, index| validate_members(record, attribute, element, prefix: "element at index #{index}: ") end else return unless value.is_a?([:container]) # TypeValidator owns the type mismatch validate_members(record, attribute, value, prefix: "") end end |