Class: RailsMcpInsight::Formatters::MermaidFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_mcp_insight/formatters/mermaid_formatter.rb

Overview

Generates Mermaid diagram syntax for Entity Relationship Diagrams.

Instance Method Summary collapse

Constructor Details

#initialize(model_analyzer) ⇒ MermaidFormatter

Returns a new instance of MermaidFormatter.



7
8
9
# File 'lib/rails_mcp_insight/formatters/mermaid_formatter.rb', line 7

def initialize(model_analyzer)
  @model_analyzer = model_analyzer
end

Instance Method Details

#generate_erd(model_names: nil) ⇒ Object

Generate an ERD for the given models (or all models if nil)



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
# File 'lib/rails_mcp_insight/formatters/mermaid_formatter.rb', line 12

def generate_erd(model_names: nil)
  models = if model_names
             model_names.filter_map { |name| @model_analyzer.analyze(name) }
           else
             @model_analyzer.list_all.filter_map { |m| @model_analyzer.analyze(m[:name]) }
           end

  return "erDiagram\n  %% No models found" if models.empty?

  lines = ["erDiagram"]

  # Add entity definitions with columns
  models.each do |model|
    lines << "  #{model[:name]} {"
    (model[:columns] || []).each do |col|
      lines << "    #{col[:type]} #{col[:name]}"
    end
    lines << "  }"
  end

  # Add relationships
  model_names_set = models.to_set { |m| m[:name] }
  models.each do |model|
    (model[:associations] || []).each do |assoc|
      target = classify(assoc[:name])
      next unless model_names_set.include?(target)

      case assoc[:type]
      when "has_many"
        lines << "  #{model[:name]} ||--o{ #{target} : \"has many\""
      when "has_one"
        lines << "  #{model[:name]} ||--|| #{target} : \"has one\""
      when "belongs_to"
        lines << "  #{model[:name]} }o--|| #{target} : \"belongs to\""
      when "has_and_belongs_to_many"
        lines << "  #{model[:name]} }o--o{ #{target} : \"HABTM\""
      end
    end
  end

  lines.join("\n")
end