Class: Kafo::DataTypes::Tuple
Instance Method Summary
collapse
#dump_default, new_from_string, parse_hash, register_type, split_arguments, types, unregister_type
Constructor Details
#initialize(*args) ⇒ Tuple
Returns a new instance of Tuple.
4
5
6
7
8
9
10
11
12
13
14
15
|
# File 'lib/kafo/data_types/tuple.rb', line 4
def initialize(*args)
if args.last.to_s =~ /\d+/ || args.last.to_s == 'default'
max = args.pop
min = args.pop
else
max = :default
min = :default
end
@max = (max.to_s == 'default') ? :infinite : max.to_i
@min = (min.to_s == 'default') ? 0 : min.to_i
@inner_types = args.map { |type| DataType.new_from_string(type) }
end
|
Instance Method Details
#condition_value(value) ⇒ Object
17
18
19
|
# File 'lib/kafo/data_types/tuple.rb', line 17
def condition_value(value)
"[ #{value.each_with_index.map { |v,i| inner_types(value)[i].condition_value(v) }.join(', ')} ]"
end
|
#multivalued? ⇒ Boolean
21
22
23
|
# File 'lib/kafo/data_types/tuple.rb', line 21
def multivalued?
true
end
|
#to_s ⇒ Object
25
26
27
28
29
30
31
32
33
34
35
36
|
# File 'lib/kafo/data_types/tuple.rb', line 25
def to_s
type = "tuple of #{@inner_types.join(', ')}"
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
38
39
40
41
42
43
44
45
46
47
|
# File 'lib/kafo/data_types/tuple.rb', line 38
def typecast(value)
if value.nil?
nil
elsif value == ['EMPTY_ARRAY']
[]
else
values = [value].flatten
values.each_with_index.map { |v,i| inner_types(values)[i].typecast(v) }
end
end
|
#valid?(input, errors = []) ⇒ Boolean
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
# File 'lib/kafo/data_types/tuple.rb', line 49
def valid?(input, errors = [])
unless input.is_a?(::Array)
errors << "#{input.inspect} is not a valid tuple"
return false
end
inner_errors = []
input.each_with_index { |v,i| inner_types(input)[i].valid?(v, inner_errors) }
unless inner_errors.empty?
errors << "Elements of the tuple are invalid: #{inner_errors.join(', ')}"
end
errors << "The tuple must have at least #{@min} items" if input.size < @min
errors << "The tuple must have at maximum #{@max} items" if @max != :infinite && input.size > @max
return errors.empty?
end
|