Skip to content

Instantly share code, notes, and snippets.

@grindars
Created July 29, 2013 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grindars/6105848 to your computer and use it in GitHub Desktop.
Save grindars/6105848 to your computer and use it in GitHub Desktop.
def render(buffer, algorithm = "dot", format = "png")
png_buffer = ""
graph_buffer = buffer.dup.force_encoding("BINARY")
png_pipe_ruby = nil
png_pipe_render = nil
graph_pipe_render = nil
graph_pipe_ruby = nil
pid = nil
status = nil
begin
graph_pipe_render, graph_pipe_ruby = IO.pipe
png_pipe_ruby, png_pipe_render = IO.pipe
pid = Process.spawn "dot", "-K", algorithm, "-T", format, "/dev/stdin",
in: graph_pipe_render,
out: png_pipe_render,
err: :err,
close_others: true
graph_pipe_render.close
graph_pipe_render = nil
png_pipe_render.close
png_pipe_render = nil
begin
loop do
begin
read_set = [ png_pipe_ruby ]
write_set = []
error_set = []
write_set << graph_pipe_ruby unless graph_buffer.empty?
read_set, write_set, error_set = IO.select read_set, write_set, error_set, nil
unless read_set.empty?
png_buffer << png_pipe_ruby.read_nonblock(8192)
end
unless write_set.empty?
bytes = graph_pipe_ruby.write_nonblock graph_buffer
graph_buffer.slice! 0, bytes
if graph_buffer.empty?
graph_pipe_ruby.close
graph_pipe_ruby = nil
end
end
rescue Errno::EWOULDBLOCK, Errno::EINTR
end
end
rescue EOFError
end
ensure
png_pipe_ruby.close unless png_pipe_ruby.nil?
png_pipe_render.close unless png_pipe_render.nil?
graph_pipe_ruby.close unless graph_pipe_ruby.nil?
graph_pipe_render.close unless graph_pipe_render.nil?
unless pid.nil?
Process.waitpid(pid)
status = $?
end
end
raise "graphviz failed" unless status.success?
png_buffer
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment