Skip to content

Commit 6fa0703

Browse files
khiav223577khiav reoy
authored and
khiav reoy
committed
Auto-detect parameters' types from example values
1 parent adb498a commit 6fa0703

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

lib/rspec_api_documentation/views/api_blueprint_index.rb

+33-1
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,11 @@ def format_route(example)
6767
# properties_description: "required, string"
6868
# }
6969
def fields(property_name, examples)
70+
possible_parameters_values = examples.map do |example|
71+
parameters = example.metadata[:extended_parameters]
72+
next parameters.map { |parameter| [parameter[:name], parameter[:value]] }.to_h
73+
end
74+
7075
examples
7176
.map { |example| example.metadata[property_name] }
7277
.flatten
@@ -79,7 +84,19 @@ def fields(property_name, examples)
7984
else
8085
properties << 'optional'
8186
end
82-
properties << property[:type] if property[:type]
87+
88+
if property.key?(:type)
89+
properties << property[:type] if property[:type]
90+
else
91+
possible_values = possible_parameters_values.map { |parameters| parameters[property[:name]] }
92+
possible_types = possible_values.map { |value| guess_type(value) }
93+
94+
possible_types.uniq!
95+
possible_types.compact!
96+
97+
properties.concat(possible_types)
98+
end
99+
83100
if properties.count > 0
84101
property[:properties_description] = properties.join(", ")
85102
else
@@ -96,6 +113,21 @@ def fields(property_name, examples)
96113
end
97114
end
98115

116+
def guess_type(value)
117+
case value
118+
when TrueClass then :boolean
119+
when FalseClass then :boolean
120+
when Array then :array
121+
when Integer then :integer
122+
when Float then :number
123+
when String then :string
124+
when Rack::Test::UploadedFile then :file
125+
when NilClass then nil
126+
else
127+
puts "Warning: unknown type of value #{value}"
128+
end
129+
end
130+
99131
# When no `description` was specified for a parameter, the DSL class
100132
# is making `description = "#{scope} #{name}"`, which is bad because it
101133
# assumes that all formats want this behavior. To avoid changing there

0 commit comments

Comments
 (0)