Class: Kafo::DataTypes::Array

Inherits:
Kafo::DataType show all
Defined in:
lib/kafo/data_types/array.rb

Instance Method Summary collapse

Methods inherited from Kafo::DataType

#dump_default, new_from_string, parse_hash, register_type, split_arguments, types, unregister_type

Constructor Details

#initialize(inner_type = 'Data', min = :default, max = :default) ⇒ Array

Returns a new instance of Array.



4
5
6
7
8
# File 'lib/kafo/data_types/array.rb', line 4

def initialize(inner_type = 'Data', min = :default, max = :default)
  @inner_type = DataType.new_from_string(inner_type)
  @min = (min.to_s == 'default') ? 0 : min.to_i
  @max = (max.to_s == 'default') ? :infinite : max.to_i
end

Instance Method Details

#condition_value(value) ⇒ Object



10
11
12
# File 'lib/kafo/data_types/array.rb', line 10

def condition_value(value)
  "[ #{value.map { |v| @inner_type.condition_value(v) }.join(', ')} ]"
end

#multivalued?Boolean

Returns:



14
15
16
# File 'lib/kafo/data_types/array.rb', line 14

def multivalued?
  true
end

#to_sObject



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/kafo/data_types/array.rb', line 18

def to_s
  type = "array of #{@inner_type}"
  if @min > 0 && @max == :infinite
    "#{type} (at least #{@min} items)"
  elsif @min == 0 && @max != :infinite
    "#{type} (up to #{@max} items)"
  elsif @min > 0 && @max != :infinite
    "#{type} (between #{@min} and #{@max} items)"
  else
    type
  end
end

#typecast(value) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/kafo/data_types/array.rb', line 31

def typecast(value)
  if value.nil?
    nil
  elsif value == ['EMPTY_ARRAY']
    []
  else
    [value].flatten.map { |v| @inner_type.typecast(v) }
  end
end

#valid?(input, errors = []) ⇒ Boolean

Returns:



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/kafo/data_types/array.rb', line 41

def valid?(input, errors = [])
  unless input.is_a?(::Array)
    errors << "#{input.inspect} is not a valid array"
    return false
  end

  inner_errors = []
  input.each { |v| @inner_type.valid?(v, inner_errors) }
  unless inner_errors.empty?
    errors << "Elements of the array are invalid: #{inner_errors.join(', ')}"
  end

  errors << "The array must have at least #{@min} items" if input.size < @min
  errors << "The array must have at maximum #{@max} items" if @max != :infinite && input.size > @max

  return errors.empty?
end