Class: RailsMermaidErd::MermaidText

Inherits:
Object
  • Object
show all
Defined in:
lib/rails-mermaid_erd/mermaid_text.rb

Constant Summary collapse

HEADER =

Renders the schema dump from RailsMermaidErd::Builder.model_data into Mermaid ‘erDiagram` source text.

This is the maximal projection of the bundled front-end viewer (lib/templates/index.html.erb): the dump always shows every table, every column with its key marker and comment, and every relation label — i.e. the diagram the viewer produces with all of its detail toggles (“Show key”, “Show comment”, “Show relation comment”) enabled and with no model-selection filtering. The viewer defaults those toggles off, so the dump is deliberately more detailed than the viewer’s initial view. The only thing it drops is the viewer’s “Restore Hash” comment line, which encodes browser-only UI state and is meaningless on the command line. Apart from that line and a single trailing newline (added by the rake task’s ‘puts`), it is byte-identical to the viewer’s “all toggles on” output.

Comment values come from arbitrary DB metadata, so they are sanitised the same way the viewer’s renderer must (and now does): newlines collapse to a space (a newline would split a label or terminate a ‘%%` line mid-diagram) and a literal `“` becomes Mermaid’s ‘#quot;` entity (an unescaped quote closes the quoted label early). Keep this byte-aligned with the viewer at index.html.erb:809-845.

[
  "erDiagram",
  "    %% --------------------------------------------------------",
  '    %% Generated by "Rails Mermaid ERD"',
  "    %% https://github.com/koedame/rails-mermaid_erd",
  "    %% --------------------------------------------------------",
  ""
].freeze

Class Method Summary collapse

Class Method Details

.build(result) ⇒ Object

‘result` is the hash returned by RailsMermaidErd::Builder.model_data.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rails-mermaid_erd/mermaid_text.rb', line 34

def build(result)
  lines = HEADER.dup

  result[:Models].each do |model|
    lines << "    %% table name: #{one_line(model[:TableName])}"
    lines << "    %% table comment: #{one_line(model[:TableComment])}"
    # Mermaid entity names can't contain ":", so namespaced models like
    # `Admin::User` are written as `Admin-User` (matches the front-end).
    lines << "    #{model[:ModelName].tr(":", "-")} {"
    model[:Columns].each do |column|
      lines << "        #{column[:type]} #{column[:name]} #{column[:key]} #{quoted(column[:comment])}"
    end
    lines << "    }"
    lines << ""
  end

  result[:Relations].each do |relation|
    left = relation[:LeftModelName].tr(":", "-")
    right = relation[:RightModelName].tr(":", "-")
    lines << "    #{left} #{relation[:LeftValue]}#{relation[:Line]}#{relation[:RightValue]} #{right} : #{quoted(relation[:Comment])}"
  end

  lines.join("\n")
end