Class: Restspec::Schema::Types::ArrayType

Inherits:
BasicType
  • Object
show all
Defined in:
lib/restspec/schema/types/array_type.rb

Instance Method Summary collapse

Methods inherited from BasicType

#initialize, #of, #to_s, #totally_valid?, #|

Constructor Details

This class inherits a constructor from Restspec::Schema::Types::BasicType

Instance Method Details

#example_for(attribute) ⇒ Array

Generates an example array.

Examples:

without a parameterized type

# schema
attribute :name, array
# examples
example_for(schema.attributes[:name])
# => []

with a parameterized type and no length example option

# schema
attribute :name, array.of(string)
# examples
example_for(schema.attributes[:name])
# => ['hola', 'mundo'] # the length is something randomly between 1 a 5.

with a parameterized type and length example option

# schema
attribute :name, array(length: 2).of(string) # or:
attribute :name, array(example_options: { length: 2}).of(string)
# examples
example_for(schema.attributes[:name])
# => ['hola', 'mundo'] # the length will always be 2

Parameters:

Returns:

  • (Array)

    Generated array for examples.



29
30
31
32
33
34
35
# File 'lib/restspec/schema/types/array_type.rb', line 29

def example_for(attribute)
  length_only_works_with_parameterized_types!

  example_length.times.map do
    parameterized_type.example_for(attribute)
  end
end

#valid?(attribute, value) ⇒ true, false

Validates if the array is valid.

  • Without a parameterized type, it only checks if the value is an array.
  • With a parameterized type, it checks is every object inside the array is valid against the parameterized type.

Parameters:

Returns:

  • (true, false)

    If the array is valid.



47
48
49
50
51
52
53
54
55
56
# File 'lib/restspec/schema/types/array_type.rb', line 47

def valid?(attribute, value)
  is_array = value.is_a?(Array)
  if parameterized_type
    is_array && value.all? do |item|
      parameterized_type.totally_valid?(attribute, item)
    end
  else
    is_array
  end
end