|
| 1 | +# encoding: utf-8 |
| 2 | +require "rails_erd/diagram" |
| 3 | +require "erb" |
| 4 | + |
| 5 | +module RailsERD |
| 6 | + class Diagram |
| 7 | + class Mermaid < Diagram |
| 8 | + |
| 9 | + attr_accessor :graph |
| 10 | + |
| 11 | + setup do |
| 12 | + self.graph = ["classDiagram"] |
| 13 | + |
| 14 | + # hard code to RL to make it easier to view diagrams from GitHub |
| 15 | + self.graph << "\tdirection RL" |
| 16 | + end |
| 17 | + |
| 18 | + each_entity do |entity, attributes| |
| 19 | + graph << "\tclass `#{entity}`" |
| 20 | + |
| 21 | + attributes.each do | attr| |
| 22 | + graph << "\t`#{entity}` : +#{attr.type} #{attr.name}" |
| 23 | + end |
| 24 | + end |
| 25 | + |
| 26 | + each_specialization do |specialization| |
| 27 | + from, to = specialization.generalized, specialization.specialized |
| 28 | + graph << "\t<<polymorphic>> `#{specialization.generalized}`" |
| 29 | + graph << "\t #{from.name} <|-- #{to.name}" |
| 30 | + end |
| 31 | + |
| 32 | + each_relationship do |relationship| |
| 33 | + from, to = relationship.source, relationship.destination |
| 34 | + graph << "\t`#{from.name}` #{relation_arrow(relationship)} `#{to.name}`" |
| 35 | + |
| 36 | + from.children.each do |child| |
| 37 | + graph << "\t`#{child.name}` #{relation_arrow(relationship)} `#{to.name}`" |
| 38 | + end |
| 39 | + |
| 40 | + to.children.each do |child| |
| 41 | + graph << "\t`#{from.name}` #{relation_arrow(relationship)} `#{child.name}`" |
| 42 | + end |
| 43 | + end |
| 44 | + |
| 45 | + save do |
| 46 | + raise "Saving diagram failed!\nOutput directory '#{File.dirname(filename)}' does not exist." unless File.directory?(File.dirname(filename)) |
| 47 | + |
| 48 | + File.write(filename.gsub(/\s/,"_"), graph.uniq.join("\n")) |
| 49 | + filename |
| 50 | + end |
| 51 | + |
| 52 | + def filename |
| 53 | + "#{options.filename}.mmd" |
| 54 | + end |
| 55 | + |
| 56 | + def relation_arrow(relationship) |
| 57 | + arrow_body = arrow_body relationship |
| 58 | + arrow_head = arrow_head relationship |
| 59 | + arrow_tail = arrow_tail relationship |
| 60 | + |
| 61 | + "#{arrow_tail}#{arrow_body}#{arrow_head}" |
| 62 | + end |
| 63 | + |
| 64 | + def arrow_body(relationship) |
| 65 | + relationship.indirect? ? ".." : "--" |
| 66 | + end |
| 67 | + |
| 68 | + def arrow_head(relationship) |
| 69 | + relationship.to_many? ? ">" : "" |
| 70 | + end |
| 71 | + |
| 72 | + def arrow_tail(relationship) |
| 73 | + relationship.many_to? ? "<" : "" |
| 74 | + end |
| 75 | + |
| 76 | + end |
| 77 | + end |
| 78 | +end |
0 commit comments