Created
April 5, 2013 08:31
-
-
Save trustin/5317595 to your computer and use it in GitHub Desktop.
A Sinatra-based webapp that retrieves the content of a gist and generates the PlantUML image URL from it.
Apparently, I'm a Ruby beginner. Please feel free to fork and make it better.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'open-uri' | |
require 'open3' | |
require 'json' | |
require 'sinatra' | |
require 'zlib' | |
$encode6bit = [ | |
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', | |
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', | |
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', | |
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', | |
'y', 'z', '-', '_' | |
] | |
configure do | |
mime_type :png, 'image/png' | |
end | |
get %r{/uml/gist/([0-9]+)} do |gist_id| | |
begin | |
cache_filename = "/var/cache/gist2uml/#{gist_id}.uml" | |
if File::exist?(cache_filename) && File::mtime(cache_filename) > Time::now - 300 | |
file = open(cache_filename) | |
umldata = file.read | |
end | |
rescue | |
ensure | |
if file | |
file.close | |
end | |
end | |
if umldata == nil | |
umldata = '' | |
begin | |
file = open("https://api.github.com/gists/#{gist_id}") | |
gist = JSON.parse(file.read) | |
if gist['files'] | |
for idx, f in gist['files'] | |
umldata = f['content'] | |
if umldata && umldata.length > 0 | |
break | |
else | |
umldata = '' | |
end | |
end | |
end | |
File.open("/var/cache/gist2uml/#{gist_id}.uml", 'w') { |f| f.write(umldata) } | |
ensure | |
if file | |
file.close | |
end | |
end | |
end | |
if !umldata.empty? | |
umldata = Zlib::Deflate.deflate(umldata, Zlib::BEST_COMPRESSION).each_byte.to_a | |
umldata_encoded = '' | |
i = 0 | |
while i < umldata.size | |
b1 = umldata[i] | |
i = i + 1 | |
b2 = if i < umldata.size then umldata[i] else 0 end | |
i = i + 1 | |
b3 = if i < umldata.size then umldata[i] else 0 end | |
i = i + 1 | |
c1 = b1 >> 2 | |
c2 = ((b1 & 0x3) << 4) | (b2 >> 4) | |
c3 = ((b2 & 0xf) << 2) | (b3 >> 6) | |
c4 = b3 & 0x3f | |
umldata_encoded << $encode6bit[c1 & 0x3f] | |
umldata_encoded << $encode6bit[c2 & 0x3f] | |
umldata_encoded << $encode6bit[c3 & 0x3f] | |
umldata_encoded << $encode6bit[c4 & 0x3f] | |
end | |
headers "Location" => "http://www.plantuml.com/plantuml/img/#{umldata_encoded}" | |
302 | |
else | |
404 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment