Skip to content

Instantly share code, notes, and snippets.

@nimrodolev
Created December 17, 2019 23:58
Show Gist options
  • Select an option

  • Save nimrodolev/bb727d7eaaa9799503321b33e0fb37bf to your computer and use it in GitHub Desktop.

Select an option

Save nimrodolev/bb727d7eaaa9799503321b33e0fb37bf to your computer and use it in GitHub Desktop.
Embed GitLab snippets in a Jekyll Markdown page using a custom Liquid tag
require 'cgi'
require 'net/https'
require 'uri'
module Jekyll
class SnippetTag < Liquid::Tag
def initialize(tag_name, text, token)
super
@text = text
@cache_disabled = false
@cache_folder = File.expand_path "../_snippet_cache", File.dirname(__FILE__)
FileUtils.mkdir_p @cache_folder
end
def render(context)
@text.strip!
snippet = @text
script_url = script_url_for(snippet)
code = get_cached_snippet(snippet) || get_snippet_from_web(snippet)
html_output_for script_url, code
end
def html_output_for(script_url, code)
code = CGI.escapeHTML code
"<script src=\"#{script_url}\"></script><div><noscript><pre><code>#{code}</code></pre></noscript></div>"
end
def script_url_for(snippet_id)
"https://gitlab.com/snippets/#{snippet_id}.js"
end
def get_snippet_url_for(snippet_id)
"https://gitlab.com/snippets/#{snippet_id}/raw"
end
def cache(snippet, data)
cache_file = get_cache_file_for snippet
File.open(cache_file, "w") do |io|
io.write data
end
end
def get_cached_snippet(snippet)
return nil if @cache_disabled
cache_file = get_cache_file_for snippet
File.read cache_file if File.exist? cache_file
end
def get_cache_file_for(snippet)
bad_chars = /[^a-zA-Z0-9\-_.]/
snippet = snippet.gsub bad_chars, ''
File.join @cache_folder, "#{snippet}.cache"
end
def get_snippet_from_web(snippet)
snippet_url = get_snippet_url_for snippet
raw_uri = URI.parse snippet_url
https = Net::HTTP.new raw_uri.host, raw_uri.port
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new raw_uri.request_uri
data = https.request request
data = data.body
cache snippet, data unless @cache_disabled
data
end
end
class SnippetTagNoCache < SnippetTag
def initialize(tag_name, text, token)
super
@cache_disabled = true
end
end
end
Liquid::Template.register_tag('snippet', Jekyll::SnippetTag)
Liquid::Template.register_tag('snippetnocache', Jekyll::SnippetTagNoCache)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment