Class: Kafo::DataTypes::Hash
Instance Method Summary
collapse
#condition_value, #dump_default, new_from_string, parse_hash, register_type, split_arguments, types, unregister_type
Constructor Details
#initialize(inner_key_type = 'Scalar', inner_value_type = 'Data', min = :default, max = :default) ⇒ Hash
Returns a new instance of Hash.
4
5
6
7
8
9
|
# File 'lib/kafo/data_types/hash.rb', line 4
def initialize(inner_key_type = 'Scalar', inner_value_type = 'Data', min = :default, max = :default)
@inner_key_type = DataType.new_from_string(inner_key_type)
@inner_value_type = DataType.new_from_string(inner_value_type)
@min = (min.to_s == 'default') ? 0 : min.to_i
@max = (max.to_s == 'default') ? :infinite : max.to_i
end
|
Instance Method Details
#multivalued? ⇒ Boolean
11
12
13
|
# File 'lib/kafo/data_types/hash.rb', line 11
def multivalued?
true
end
|
#to_s ⇒ Object
15
16
17
18
19
20
21
22
23
24
25
26
|
# File 'lib/kafo/data_types/hash.rb', line 15
def to_s
type = "hash of #{@inner_key_type}/#{@inner_value_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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
# File 'lib/kafo/data_types/hash.rb', line 28
def typecast(value)
if value.nil?
nil
elsif value.is_a?(::Hash)
value
elsif value == ['EMPTY_HASH']
{}
else
::Hash[[value].flatten.map do |kv|
k, v = kv.split(':', 2)
[@inner_key_type.typecast(k), @inner_value_type.typecast(v)]
end]
end
end
|
#valid?(input, errors = []) ⇒ Boolean
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
# File 'lib/kafo/data_types/hash.rb', line 43
def valid?(input, errors = [])
unless input.is_a?(::Hash)
errors << "#{input.inspect} is not a valid hash"
return false
end
inner_key_errors = []
input.keys.each { |v| @inner_key_type.valid?(v, inner_key_errors) }
unless inner_key_errors.empty?
errors << "Hash key elements are invalid: #{inner_key_errors.join(', ')}"
end
inner_value_errors = []
input.values.each { |v| @inner_value_type.valid?(v, inner_value_errors) }
unless inner_value_errors.empty?
errors << "Hash value elements are invalid: #{inner_value_errors.join(', ')}"
end
errors << "The hash must have at least #{@min} items" if input.size < @min
errors << "The hash must have at maximum #{@max} items" if @max != :infinite && input.size > @max
return errors.empty?
end
|