Class: RailsMcpInsight::Analyzers::ModelAnalyzer

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_mcp_insight/analyzers/model_analyzer.rb

Overview

Analyzes Rails model files to extract associations, validations, callbacks, scopes, and column information from schema.rb.

Instance Method Summary collapse

Constructor Details

#initialize(config, ast_parser: AstParser.new) ⇒ ModelAnalyzer

Returns a new instance of ModelAnalyzer.



8
9
10
11
12
# File 'lib/rails_mcp_insight/analyzers/model_analyzer.rb', line 8

def initialize(config, ast_parser: AstParser.new)
  @config = config
  @ast_parser = ast_parser
  @schema_cache = nil
end

Instance Method Details

#analyze(model_name) ⇒ Object

Analyze a specific model by name (e.g., "Order", "User")



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
# File 'lib/rails_mcp_insight/analyzers/model_analyzer.rb', line 15

def analyze(model_name)
  file_path = find_model_file(model_name)
  return nil unless file_path

  parsed = @ast_parser.parse_file(file_path)
  return nil unless parsed

  table_name = model_name_to_table(model_name)
  columns = extract_columns(table_name)

  {
    name: model_name,
    file: relative_path(file_path),
    parent_class: parsed.classes.first&.parent || "ApplicationRecord",
    table_name: table_name,
    columns: columns,
    associations: extract_associations(parsed),
    validations: extract_validations(parsed),
    callbacks: extract_callbacks(parsed),
    scopes: extract_scopes(parsed),
    concerns: parsed.includes.map { |i| i[:module] },
    enums: extract_enums(parsed),
    class_methods: parsed.methods.select { |m| m.name.start_with?("self.") }.map(&:name),
    instance_methods: parsed.methods.reject { |m| m.name.start_with?("self.") }.map do |m|
      { name: m.name, visibility: m.visibility, line: m.line }
    end,
    indexes: extract_indexes(table_name)
  }
end

#list_allObject

List all models in the project



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/rails_mcp_insight/analyzers/model_analyzer.rb', line 46

def list_all
  models_dir = @config.models_path
  return [] unless Dir.exist?(models_dir)

  Dir.glob(File.join(models_dir, "**", "*.rb")).filter_map do |file|
    parsed = @ast_parser.parse_file(file)
    next unless parsed&.classes&.any?

    klass = parsed.classes.first
    table_name = model_name_to_table(klass.name)

    {
      name: klass.name,
      file: relative_path(file),
      parent_class: klass.parent || "ApplicationRecord",
      table_name: table_name,
      column_count: extract_columns(table_name).length,
      association_count: extract_associations(parsed).length
    }
  end
end