37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
|
# File 'lib/jddf/schema.rb', line 37
def self.from_json(hash)
raise TypeError.new, 'hash must be a Hash' unless hash.is_a?(Hash)
schema = Schema.new
if hash.include?('definitions')
unless hash['definitions'].is_a?(Hash)
raise TypeError, 'definitions not Hash'
end
schema.definitions = hash['definitions'].map do |key, schema|
[key, from_json(schema)]
end.to_h
end
if hash.include?('ref')
raise TypeError, 'ref not String' unless hash['ref'].is_a?(String)
schema.ref = hash['ref']
end
if hash.include?('type')
raise TypeError, 'type not String' unless hash['type'].is_a?(String)
unless TYPES.map(&:to_s).include?(hash['type'])
raise TypeError, "type not in #{TYPES}"
end
schema.type = hash['type'].to_sym
end
if hash.include?('enum')
raise TypeError, 'enum not Array' unless hash['enum'].is_a?(Array)
raise ArgumentError, 'enum is empty array' if hash['enum'].empty?
hash['enum'].each do |value|
raise TypeError, 'enum element not String' unless value.is_a?(String)
end
schema.enum = hash['enum'].to_set
if schema.enum.size != hash['enum'].size
raise ArgumentError, 'enum contains duplicates'
end
end
if hash.include?('elements')
raise TypeError, 'elements not Hash' unless hash['elements'].is_a?(Hash)
schema.elements = from_json(hash['elements'])
end
if hash.include?('properties')
unless hash['properties'].is_a?(Hash)
raise TypeError, 'properties not Hash'
end
schema.properties = hash['properties'].map do |key, schema|
[key, from_json(schema)]
end.to_h
end
if hash.include?('optionalProperties')
unless hash['optionalProperties'].is_a?(Hash)
raise TypeError, 'optionalProperties not Hash'
end
optional_properties = hash['optionalProperties'].map do |key, schema|
[key, from_json(schema)]
end.to_h
schema.optional_properties = optional_properties
end
if hash.include?('additionalProperties')
unless [true, false].include?(hash['additionalProperties'])
raise TypeError, 'additionalProperties not boolean'
end
schema.additional_properties = hash['additionalProperties']
end
if hash.include?('values')
raise TypeError, 'values not Hash' unless hash['values'].is_a?(Hash)
schema.values = from_json(hash['values'])
end
if hash.include?('discriminator')
unless hash['discriminator'].is_a?(Hash)
raise TypeError, 'discriminator not Hash'
end
schema.discriminator = Discriminator.from_json(hash['discriminator'])
end
schema
end
|