Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions lib/apipie/validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
54 changes: 54 additions & 0 deletions spec/lib/validators/array_of_validator_spec.rb
Original file line number Diff line number Diff line change
@@ -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