forked from sendgrid/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiv3_example.rb
More file actions
92 lines (76 loc) · 2.58 KB
/
Copy pathapiv3_example.rb
File metadata and controls
92 lines (76 loc) · 2.58 KB
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
module Jekyll
class ApiV3Example < Liquid::Block
def initialize(tag_name, markup, tokens)
attributes = markup.split
@identifier = attributes[0]
@request_type = attributes[1]
@url = attributes[2]
@data = markup.gsub(attributes[0],"").gsub(attributes[1],"").gsub(attributes[2],"").strip
if attributes[4]
@show_livedoc = attributes[4]
end
super
end
def render(context)
output = super
output = <<HTML
<div class="api-example panel" id="apiv3example-#{@identifier}">
#{output}
</div>
HTML
return Liquid::Template.parse(output).render context
end
def render_all(list, context)
context['identifier'] = @identifier
context['request_type'] = @request_type
context['url'] = @url
context['data'] = @data
super
end
end
class V3ResponseBlock < Liquid::Block
# Solution to unquote true, false, and numbers in JSON response
def unquote_data(data)
data.each do |k, v|
unless v.index("]").nil?
data[k] = v[v.index("[") + 1, v.index("]") - 1].gsub!("'", "")
data[k] = data[k].split(",")
end
data[k] = v.to_i if /\A[-+]?\d+\z/ === v
data[k] = true if v == "true"
data[k] = false if v == "false"
end
end
def render(context)
output = super
# let's parse the vars before we generate the output to avoid complications
identifier = Liquid::Template.parse("{{ identifier }}").render context
request_type = Liquid::Template.parse("{{ request_type }}").render context
url = Liquid::Template.parse("{{ url }}").render context
data = Liquid::Template.parse("{{ data }}").render context
if data.include? "="
data = Hash[URI.decode_www_form(data)]
data = unquote_data(data)
data = data.length > 0 ? JSON.pretty_generate(data) : ""
else
data = data.length > 0 ? JSON.pretty_generate(JSON.parse(data)) : ""
end
if data.length > 0
data_block = "Request Body<br/>{% codeblock lang:json %}#{data}{% endcodeblock %}"
end
request_url = url
output = <<HTML
<div class="panel-body">
<h3>Request</h3>
{% codeblock lang:http %}#{request_type} #{request_url} HTTP/1.1{% endcodeblock %}
#{data_block}
<h3>Response</h3>
{% codeblock lang:json %}#{output.strip}{% endcodeblock %}
</div>
HTML
return Liquid::Template.parse(output).render context
end
end
end
Liquid::Template.register_tag('v3response', Jekyll::V3ResponseBlock)
Liquid::Template.register_tag('apiv3example', Jekyll::ApiV3Example)