Class: Ivar::ProjectRoot

Inherits:
Object
  • Object
show all
Defined in:
lib/ivar/project_root.rb

Overview

Handles project root detection and caching

Constant Summary collapse

INDICATORS =

Project root indicator files, in order of precedence

%w[Gemfile .git .ruby-version Rakefile].freeze

Instance Method Summary collapse

Constructor Details

#initializeProjectRoot

Returns a new instance of ProjectRoot.



11
12
13
14
# File 'lib/ivar/project_root.rb', line 11

def initialize
  @cache = {}
  @mutex = Mutex.new
end

Instance Method Details

#clear_cacheObject

Clear the cache (mainly for testing)



38
39
40
# File 'lib/ivar/project_root.rb', line 38

def clear_cache
  @mutex.synchronize { @cache.clear }
end

#find(caller_location = nil) ⇒ String

Determines the project root directory based on the caller’s location

Parameters:

  • caller_location (String, nil) (defaults to: nil)

    Optional file path to start from (defaults to caller’s location)

Returns:

  • (String)

    The absolute path to the project root directory



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/ivar/project_root.rb', line 19

def find(caller_location = nil)
  file_path = caller_location || caller_locations(2, 1).first&.path
  return Dir.pwd unless file_path

  @mutex.synchronize do
    return @cache[file_path] if @cache.key?(file_path)
  end

  dir = File.dirname(File.expand_path(file_path))
  root = find_project_root(dir)

  @mutex.synchronize do
    @cache[file_path] = root
  end

  root
end