Class: Lernen::Graph

Inherits:
Object
  • Object
show all
Defined in:
lib/lernen/graph.rb

Overview

Graph represents a labelled directed graph.

This is an intermediate data structure for rendering Mermaid and Graphviz diagrams.

Constant Summary collapse

Node =

Node represents a node of graphs.

Data.define(:label, :shape)
Edge =

Edge represents an edge of graphs.

Data.define(:from, :label, :to)
SubGraph =

SubGraph represents a sub-graph of graphs.

Data.define(:label, :graph)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nodes, edges, subgraphs = []) ⇒ Graph

: (

  Hash[Integer, Node] nodes,
  Array[Edge] edges,
  ?Array[SubGraph] subgraphs
) -> void


96
97
98
99
100
# File 'lib/lernen/graph.rb', line 96

def initialize(nodes, edges, subgraphs = [])
  @nodes = nodes
  @edges = edges
  @subgraphs = subgraphs
end

Instance Attribute Details

#edgesObject (readonly)

: Array



103
104
105
# File 'lib/lernen/graph.rb', line 103

def edges
  @edges
end

#nodesObject (readonly)

: Hash[Integer, Node]



102
103
104
# File 'lib/lernen/graph.rb', line 102

def nodes
  @nodes
end

#subgraphsObject (readonly)

: Array



104
105
106
# File 'lib/lernen/graph.rb', line 104

def subgraphs
  @subgraphs
end

Class Method Details

.dot_escape(label) ⇒ Object

Returns the escaped string for GraphViz DOTs.

See graphviz.org/docs/attr-types/escString/.

: (String label) -> String



74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/lernen/graph.rb', line 74

def self.dot_escape(label)
  label =
    label.gsub(/[\\"]/) do |c|
      case c
      in "\\"
        "\\\\"
      in "\""
        "\\\""
      end
    end
  "\"#{label}\""
end

.mermaid_escape(label) ⇒ Object

Returns the escaped string for Mermaid diagrams.

See mermaid.js.org/syntax/flowchart.html#entity-codes-to-escape-characters.

: (String label) -> String



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/lernen/graph.rb', line 56

def self.mermaid_escape(label)
  label =
    label.gsub(/[#"]/) do |c|
      case c
      in "#"
        "#35;"
      in "\""
        "#quot;"
      end
    end
  "\"#{label}\""
end

Instance Method Details

#to_dotObject

Returns a [GraphViz](graphviz.org) DOT diagram of this graph.

: () -> String



121
122
123
124
125
126
127
128
129
# File 'lib/lernen/graph.rb', line 121

def to_dot
  dot = +""

  dot << "digraph {\n"
  dot << to_dot_internal
  dot << "}\n"

  dot.freeze
end

#to_mermaid(direction: "TD") ⇒ Object

Returns a [Mermaid](mermaid.js.org) diagram of this graph.

: (?direction: mermaid_direction) -> String



109
110
111
112
113
114
115
116
# File 'lib/lernen/graph.rb', line 109

def to_mermaid(direction: "TD")
  mmd = +""

  mmd << "flowchart #{direction}\n"
  mmd << to_mermaid_internal

  mmd.freeze
end