Sha256: f07b4a3dd3da6ea1b85d3ab6b6d624350110a983949321f989520b14881bfdbb

Contents?: true

Size: 1.44 KB

Versions: 2

Compression:

Stored size: 1.44 KB

Contents

require 'open3'

module Jekyll
  module Diagrams
    class GraphvizBlock < Liquid::Block
      def initialize(tag_name, text, tokens)
        super
        @tag_name = tag_name
        @engine = text.strip
      end

      def render(context)
        config = context.registers[:site].config["diagrams"]

        @renderer = GraphvizRenderer.new(config["graphviz"])

        render_diagram(super)
      end

      private

      def render_diagram(code)
        code = case @tag_name
        when 'graph', 'digraph'
          "#@tag_name {\n#{code}\n}"
        when 'graphviz'
          code
        else
          raise "unknown liquid tag name: #{@tag_name}"
        end

        @renderer.render(code, @engine)
      end
    end

    class GraphvizRenderer
      DEFAULTS = {
        'engine'  => 'dot',
        'options' => '-Tsvg'
      }

      def initialize(config)
        @config = DEFAULTS.merge(config)
      end

      def render(code, engine = DEFAULTS['engine'])
        cmd = "#{@config['engine']} #{@config['options']}"
        svg, status = Open3.capture2(
          cmd,
          stdin_data: code,
          binmode: true
        )

        if !status.success?
          raise "Non-zero exit status '#{cmd}': #{status}"
        end

        svg.force_encoding 'UTF-8'

        "<div class='graphviz'>#{svg}</div>"
      end
    end
  end
end

%w(graphviz graph digraph).each do |tag|
  Liquid::Template.register_tag(tag, Jekyll::Diagrams::GraphvizBlock)
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
jekyll-diagrams-0.4.1 lib/jekyll/diagrams/graphviz.rb
jekyll-diagrams-0.4.0 lib/jekyll/diagrams/graphviz.rb