aboutsummaryrefslogtreecommitdiff
path: root/_plugins/graphviz-block.rb
blob: 4ddd2eeb3831ec431ee66e0a1bd9018b3ebe240d (about) (plain) (blame)
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
require 'tempfile'
require 'digest'

OUTPUT_DIR = '/images/graphviz'

module Jekyll
  class GraphvizBlock < Liquid::Block
    def initialize(tag_name, options, tokens)
      super
      opts_list = options.split('|').map { |s| s.strip }
      @name = opts_list[0]
      @alt = opts_list[1]
    end

    def render(context)
      source = super
      site = context.registers[:site]
      FileUtils.mkdir_p(File.join(site.source, OUTPUT_DIR))

      filename = "#{@name}-#{Digest::SHA256.hexdigest(source + @alt)}.svg"
      site_path = File.join(OUTPUT_DIR, filename)
      os_path = File.join(site.source, site_path)

      f = Tempfile.new('graphviz-input')
      f.write(source)
      f.close
      `dot -Tsvg #{f.path} > #{os_path}`
      f.unlink

      site.static_files << Jekyll::StaticFile.new(site, site.source, OUTPUT_DIR, filename)
      "<img src=\"#{site_path}\" alt=\"#{@alt}\" />"
    end
  end
end

Liquid::Template.register_tag('graphviz', Jekyll::GraphvizBlock)