-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathgraphviz_presenter.rb
79 lines (72 loc) · 1.53 KB
/
graphviz_presenter.rb
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class GraphvizPresenter < GraphPresenter
def to_gv
[
"digraph MyFlow {",
'',
'## LABELS',
'',
label_lines,
'',
'## EDGES',
'',
edge_lines,
metadata_lines,
"}"
].flatten.join("\n")
end
def label_lines
labels.map do |name, label|
attrs = {
label: escape(label),
shape: "box"
}
if is_first?(name)
attrs.merge!(
color: "gold1",
style: "filled"
)
elsif is_outcome?(name)
attrs.merge!(
color: "aquamarine",
style: "filled"
)
end
attribute_clause = attrs.map { |k, v| "#{k}=\"#{v}\"" }.join(' ')
%Q{#{normalize_name(name)} [#{attribute_clause}]}
end
end
def is_first?(node_name)
@flow.questions.first.name == node_name
end
def is_outcome?(node_name)
@flow.outcomes.map(&:name).include?(node_name)
end
def edge_lines
adjacency_list.map do |name, exits|
exits.map do |nextnode, label|
next unless nextnode
%Q{#{normalize_name(name)}->#{normalize_name(nextnode)} [label="#{label}"];}
end
end.flatten
end
def metadata_lines
[
'overlap=false;',
'splines=true;',
%Q{label="#{escape(presenter.title)}";},
'fontsize=12;'
]
end
def escape(label)
map = {
"\n" => '\n',
"[" => '\[',
"]" => '\]',
'"' => '\''
}
label.to_s.gsub(%r{[\n\[\]"]}, map)
end
def normalize_name(name)
name.to_s.gsub(/[^a-zA-Z0-9_]/, "")
end
end