Skip to content

Commit b9ca700

Browse files
authored
feat(ruby): determine JSONSchema type from const/enum (#667)
The Schema class now infers the type of a schema object when "const" or "enum" is used. If "const" or "enum" are present, any "type" field is ignored. needed by #636
1 parent 2f83ef6 commit b9ca700

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

lib/arch_obj_models/schema.rb

+26-1
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,34 @@ def initialize(schema_hash)
1616
# @return [Hash] Hash representation of the JSON Schema
1717
def to_h = @schema_hash
1818

19+
def rb_obj_to_jsonschema_type(rb_type)
20+
case rb_type
21+
when String
22+
"string"
23+
when Integer
24+
"integer"
25+
when Number
26+
"number"
27+
when Array
28+
"array"
29+
when Hash
30+
"object"
31+
else
32+
raise "TODO: unsupported const type for '#{@schema_hash['const']}'"
33+
end
34+
end
35+
private :rb_obj_to_jsonschema_type
36+
1937
# @return [String] Human-readable type of the schema (e.g., array, string, integer)
2038
def type_pretty
21-
@schema_hash["type"]
39+
if @schema_hash.key?("const")
40+
rb_obj_to_jsonschema_type(@schema_hash["const"])
41+
elsif @schema_hash.key?("enum") && !@schema_hash["enum"].empty? && @schema_hash["enum"].all? { |elem| elem.class == @schema_hash["enum"][0].class }
42+
rb_obj_to_jsonschema_type(@schema_hash["enum"][0])
43+
else
44+
raise "Missing type information for '#{@schema_hash}'" unless @schema_hash.key?("type")
45+
@schema_hash["type"]
46+
end
2247
end
2348

2449
# @return [String] A human-readable description of the schema

0 commit comments

Comments
 (0)