-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathapi_reference_extension.rb
100 lines (82 loc) · 2.45 KB
/
api_reference_extension.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
require "erb"
require "openapi3_parser"
require "uri"
require "govuk_tech_docs/api_reference/api_reference_renderer"
module GovukTechDocs
module ApiReference
class Extension < Middleman::Extension
expose_to_application api: :api
def initialize(app, options_hash = {}, &block)
super
@app = app
@config = @app.config[:tech_docs]
# If no api path then just return.
if @config["api_path"].to_s.empty?
@api_parser = false
return
end
# Is the api_path a url or path?
if uri?(@config["api_path"])
@api_parser = true
@document = Openapi3Parser.load_url(@config["api_path"])
elsif File.exist?(@config["api_path"])
# Load api file and set existence flag.
@api_parser = true
@document = Openapi3Parser.load_file(@config["api_path"])
else
@api_parser = false
raise "Unable to load api path from tech-docs.yml"
end
@render = Renderer.new(@app, @document)
end
def uri?(string)
uri = URI.parse(string)
%w[http https].include?(uri.scheme)
rescue URI::BadURIError
false
rescue URI::InvalidURIError
false
end
def api(text)
if @api_parser == true
keywords = {
"api>" => "default",
"api_schema>" => "schema",
}
regexp = keywords.map { |k, _| Regexp.escape(k) }.join("|")
md = text.match(/^<p>(#{regexp})/)
if md
key = md.captures[0]
type = keywords[key]
text.gsub!(/#{Regexp.escape(key)}\s+?/, "")
# Strip paragraph tags from text
text = text.gsub(/<\/?[^>]*>/, "")
text = text.strip
if text == "api>"
@render.api_full(api_info, api_servers)
elsif type == "default"
output = @render.path(text)
# Render any schemas referenced in the above path
output += @render.schemas_from_path(text)
output
else
@render.schema(text)
end
else
text
end
else
text
end
end
private
def api_info
@document.info
end
def api_servers
@document.servers
end
end
end
end
::Middleman::Extensions.register(:api_reference, GovukTechDocs::ApiReference::Extension)