/
jekyll_example_embed.rb
75 lines (58 loc) · 1.86 KB
/
jekyll_example_embed.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
module Jekyll
class ExampleEmbedTag < Liquid::Tag
def initialize(tag_name, text, tokens)
@example = text.strip
super
end
def render(context)
@context = context
lang, name = @example.split('/')
coerce_documents!
document = collection.docs.detect do |document|
document.relative_path == "_examples/#{@example}"
end
if document.nil?
puts "** ERROR: Could not find example #{@example}\n"
return
end
highlight = context.stack do
wrapped_content = "{% highlight #{lang} %}#{document.content}{% endhighlight %}"
Liquid::Template.parse(wrapped_content).render!(context)
end
[ "<h4>#{name}</h4>",
'<h5>Source</h5>',
highlight,
'<h5>Result</h5>',
%{<iframe src="#{document.url}" frameBorder="0" onload="#{auto_resize}"></iframe>}
].join("\n")
end
private
def coerce_documents!
collection.files.reduce(collection.docs) do |memo, file|
memo << file2doc(file)
end
collection.files.slice!(0, collection.files.length)
end
def collection
@context.registers[:site].collections['examples']
end
def file2doc(file)
site = @context.registers[:site]
document = Jekyll::Document.new(file.path, {
site: site,
collection: @context.registers[:site].collections['examples']
}).tap(&:read)
document.content.tap do |content|
document.output = Jekyll::Renderer.new(site, document, nil).run
document.content = content
end
document
end
def auto_resize
["this.height = this.contentWindow.document.body.scrollHeight + 'px'",
"this.width = this.contentWindow.document.body.scrollWidth + 'px'"
].join(';')
end
Liquid::Template.register_tag('example_embed', Jekyll::ExampleEmbedTag)
end
end