Class: RailsMcpInsight::Analyzers::CodeSearcher

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

Overview

Searches code across the project with regex support and context lines.

Constant Summary collapse

IGNORE_DIRS =

Files/dirs to always skip

[".git", "node_modules", "tmp", "log", "vendor/bundle", "coverage", ".bundle"].freeze
BINARY_EXTENSIONS =
[".png", ".jpg", ".jpeg", ".gif", ".ico", ".pdf", ".zip", ".tar", ".gz", ".woff", ".woff2",
".ttf", ".eot", ".svg"].freeze

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ CodeSearcher

Returns a new instance of CodeSearcher.



12
13
14
# File 'lib/rails_mcp_insight/analyzers/code_searcher.rb', line 12

def initialize(config)
  @config = config
end

Instance Method Details

#find_definition(symbol:, type: nil) ⇒ Object

Find the definition of a symbol (class, module, method, constant)



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

def find_definition(symbol:, type: nil)
  pattern = case type
            when "class" then /^\s*class\s+#{Regexp.escape(symbol)}\b/
            when "module" then /^\s*module\s+#{Regexp.escape(symbol)}\b/
            when "method" then /^\s*def\s+(?:self\.)?#{Regexp.escape(symbol)}\b/
            when "constant" then /^\s*#{Regexp.escape(symbol)}\s*=/
            else
              /^\s*(?:class|module|def\s+(?:self\.)?|)#{Regexp.escape(symbol)}\b/
            end

  results = []
  Dir.glob(File.join(@config.project_path, "**", "*.rb")).each do |file|
    next if should_skip?(file)

    content = File.read(file)
    content.lines.each_with_index do |line, idx|
      next unless line.match?(pattern)

      results << {
        file: relative_path(file),
        line: idx + 1,
        definition: line.strip,
        type: detect_definition_type(line)
      }
    end
  end

  results
end

#search(query:, file_pattern: "*.rb", context_lines: 2, max_results: 50) ⇒ Object

Search for a query across the project



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rails_mcp_insight/analyzers/code_searcher.rb', line 17

def search(query:, file_pattern: "*.rb", context_lines: 2, max_results: 50)
  results = []
  search_path = @config.project_path

  Dir.glob(File.join(search_path, "**", file_pattern)).each do |file|
    next if should_skip?(file)
    next if binary_file?(file)

    matches = search_file(file, query, context_lines)
    matches.each do |match|
      results << match.merge(file: relative_path(file))
    end

    break if results.length >= max_results
  end

  {
    query: query,
    file_pattern: file_pattern,
    total_matches: results.length,
    truncated: results.length >= max_results,
    results: results.first(max_results)
  }
end