Class: Aidp::PromptOptimization::SourceCodeFragmenter

Inherits:
Object
  • Object
show all
Defined in:
lib/aidp/prompt_optimization/source_code_fragmenter.rb

Overview

Fragments source code files into retrievable code units

Parses Ruby source files and extracts methods, classes, modules along with their dependencies and imports. Each fragment can be independently included or excluded from prompts.

Examples:

Basic usage

fragmenter = SourceCodeFragmenter.new(project_dir: "/path/to/project")
fragments = fragmenter.fragment_file("lib/my_file.rb")

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(project_dir:) ⇒ SourceCodeFragmenter

Returns a new instance of SourceCodeFragmenter.



17
18
19
# File 'lib/aidp/prompt_optimization/source_code_fragmenter.rb', line 17

def initialize(project_dir:)
  @project_dir = project_dir
end

Instance Attribute Details

#project_dirObject (readonly)

Returns the value of attribute project_dir.



15
16
17
# File 'lib/aidp/prompt_optimization/source_code_fragmenter.rb', line 15

def project_dir
  @project_dir
end

Instance Method Details

#fragment_file(file_path, context_lines: 2) ⇒ Array<CodeFragment>

Fragment a source file into code units

Parameters:

  • file_path (String)

    Path to source file (relative or absolute)

  • context_lines (Integer) (defaults to: 2)

    Number of context lines around code units

Returns:



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/aidp/prompt_optimization/source_code_fragmenter.rb', line 26

def fragment_file(file_path, context_lines: 2)
  abs_path = File.absolute_path?(file_path) ? file_path : File.join(@project_dir, file_path)

  return [] unless File.exist?(abs_path)
  return [] unless abs_path.end_with?(".rb")

  content = File.read(abs_path)
  fragments = []

  # Extract requires/imports as first fragment
  requires = extract_requires(content)
  if requires && !requires.empty?
    fragments << create_requires_fragment(abs_path, requires)
  end

  # Extract classes and modules
  fragments.concat(extract_classes_and_modules(abs_path, content))

  # Extract top-level methods
  fragments.concat(extract_methods(abs_path, content, context_lines: context_lines))

  fragments
end

#fragment_files(file_paths) ⇒ Array<CodeFragment>

Fragment multiple files

Parameters:

  • file_paths (Array<String>)

    List of file paths

Returns:



54
55
56
# File 'lib/aidp/prompt_optimization/source_code_fragmenter.rb', line 54

def fragment_files(file_paths)
  file_paths.flat_map { |path| fragment_file(path) }
end