diff --git a/lib/apipie/validator.rb b/lib/apipie/validator.rb index e4bfa0e65..3c03658c9 100644 --- a/lib/apipie/validator.rb +++ b/lib/apipie/validator.rb @@ -247,6 +247,50 @@ def description end end + class ArrayOfValidator < Apipie::Validator::BaseValidator + class << self + def for_class + :array_of_validator + end + + def build(param_description, argument, options, block) + if argument == for_class + new(param_description, options, block) + end + end + end + + def initialize(param_description, options, block) + super(param_description) + @items_type = options[:of] + @options = options + @block = block + end + + def validate(values) + values ||= [] + return false unless values.respond_to?(:each) && !values.is_a?(String) + values.all? { |v| validate_item(v) } + end + + def validate_item(value) + Apipie::Validator::BaseValidator.find( + param_description, + items_type, + options, + block, + ).validate(value) + end + + def description + "Must be array of #{items_type}s." + end + + private + + attr_reader :items_type, :param_description, :options, :block + end + class ProcValidator < BaseValidator def initialize(param_description, argument) diff --git a/spec/lib/validators/array_of_validator_spec.rb b/spec/lib/validators/array_of_validator_spec.rb new file mode 100644 index 000000000..8ad7bf4a8 --- /dev/null +++ b/spec/lib/validators/array_of_validator_spec.rb @@ -0,0 +1,54 @@ +require "spec_helper" + +module Apipie::Validator + describe ArrayOfValidator do + let(:options) { { of: Integer } } + let(:validator) do + described_class.new( + "param_description", + options, + proc {}, + ) + end + + class << self + def it_returns_true + it "returns true" do + expect(validator.validate(value)).to be_truthy + end + end + + def it_returns_false + it "returns false" do + expect(validator.validate(value)).to be_falsey + end + end + end + + describe "#validate" do + context "nil" do + let(:value) { nil } + + it_returns_true + end + + context "empty array" do + let(:value) { [] } + + it_returns_true + end + + context "contains desired type" do + let(:value) { [1] } + + it_returns_true + end + + context "contains wrong type" do + let(:value) { [1, "a"] } + + it_returns_false + end + end + end +end