dot_helper.rb 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. module DotHelper
  2. def render_agents_diagram(agents)
  3. if (command = ENV['USE_GRAPHVIZ_DOT']) &&
  4. (svg = IO.popen([command, *%w[-Tsvg -q1 -o/dev/stdout /dev/stdin]], 'w+') { |dot|
  5. dot.print agents_dot(agents, true)
  6. dot.close_write
  7. dot.read
  8. } rescue false)
  9. svg.html_safe
  10. else
  11. tag('img', src: URI('https://chart.googleapis.com/chart').tap { |uri|
  12. uri.query = URI.encode_www_form(cht: 'gv', chl: agents_dot(agents))
  13. })
  14. end
  15. end
  16. private
  17. def dot_id(string)
  18. # Backslash escaping seems to work for the backslash itself,
  19. # despite the DOT language document.
  20. '"%s"' % string.gsub(/\\/, "\\\\\\\\").gsub(/"/, "\\\\\"")
  21. end
  22. def agents_dot(agents, rich = false)
  23. "digraph foo {".tap { |dot|
  24. agents.each.with_index do |agent, index|
  25. if rich
  26. dot << '%s[URL=%s];' % [dot_id(agent.name), dot_id(agent_path(agent.id))]
  27. else
  28. dot << '%s;' % dot_id(agent.name)
  29. end
  30. agent.receivers.each do |receiver|
  31. dot << "%s->%s;" % [dot_id(agent.name), dot_id(receiver.name)]
  32. end
  33. end
  34. dot << "}"
  35. }
  36. end
  37. end