Class: ReferenceExtractor::Extractor

Inherits:
Object
  • Object
show all
Defined in:
lib/reference_extractor/extractor.rb

Overview

Public API for extracting constant references from Ruby code (that is autoloaded via Zeitwerk).

Examples:

extractor = ReferenceExtractor::Extractor.new(autoloaders: Rails.autoloaders, root_path: Rails.root)
references = extractor.references_from_string("Order.find(1)")
references = extractor.references_from_file("app/models/user.rb")

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(autoloaders:, root_path:) ⇒ Extractor

Returns a new instance of Extractor.

Parameters:

  • autoloaders (Enumerable)

    Collection of Zeitwerk loaders, e.g. from ‘Rails.autoloaders`

  • root_path (String, Pathname)

    The root path of the application, e.g. from ‘Rails.root`



15
16
17
18
19
# File 'lib/reference_extractor/extractor.rb', line 15

def initialize(autoloaders:, root_path:)
  @autoloaders = autoloaders
  @root_path = Pathname.new(root_path)
  @context_provider = Internal::ConstantDiscovery.new(root_path:, loaders: @autoloaders)
end

Instance Attribute Details

#root_pathObject (readonly)

Returns the value of attribute root_path.



11
12
13
# File 'lib/reference_extractor/extractor.rb', line 11

def root_path
  @root_path
end

Instance Method Details

#references_from_file(file_path) ⇒ Array<Reference>

Extract constant references from a Ruby file.

Parameters:

  • file_path (String, Pathname)

    Path to the Ruby file (relative to root_path or absolute)

Returns:

  • (Array<Reference>)

    Array of references to autoloaded constants in project files



36
37
38
39
40
41
42
43
44
45
# File 'lib/reference_extractor/extractor.rb', line 36

def references_from_file(file_path)
  absolute_path = Pathname.new(file_path).expand_path(root_path)
  return [] unless File.exist?(absolute_path)

  ast = parse_file(absolute_path)
  return [] unless ast

  relative_path = Pathname.new(absolute_path).relative_path_from(root_path).to_s
  extract_references(ast, relative_path:)
end

#references_from_string(snippet) ⇒ Array<Reference>

Extract constant references from a Ruby code string.

Parameters:

  • snippet (String)

    The Ruby code to analyze

Returns:

  • (Array<Reference>)

    Array of references to autoloaded constants in project files



25
26
27
28
29
30
# File 'lib/reference_extractor/extractor.rb', line 25

def references_from_string(snippet)
  ast = parse_ruby_string(snippet)
  return [] unless ast

  extract_references(ast, relative_path: "<snippet>")
end