Module: CodeOwnership::Private::FilePathFinder

Extended by:
T::Sig
Defined in:
lib/code_ownership/private/file_path_finder.rb

Class Method Summary collapse

Class Method Details

.from_backtrace(backtrace) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/code_ownership/private/file_path_finder.rb', line 22

def self.from_backtrace(backtrace)
  return [] unless backtrace

  # The pattern for a backtrace hasn't changed in forever and is considered
  # stable: https://github.com/ruby/ruby/blob/trunk/vm_backtrace.c#L303-L317
  #
  # This pattern matches a line like the following:
  #
  #   ./app/controllers/some_controller.rb:43:in `block (3 levels) in create'
  #
  backtrace_line = if RUBY_VERSION >= '3.4.0'
                     %r{\A(#{Pathname.pwd}/|\./)?
                         (?<file>.+)       # Matches 'app/controllers/some_controller.rb'
                         :
                         (?<line>\d+)      # Matches '43'
                         :in\s
                         '(?<function>.*)' # Matches "`block (3 levels) in create'"
                       \z}x
                   else
                     %r{\A(#{Pathname.pwd}/|\./)?
                         (?<file>.+)       # Matches 'app/controllers/some_controller.rb'
                         :
                         (?<line>\d+)      # Matches '43'
                         :in\s
                         `(?<function>.*)' # Matches "`block (3 levels) in create'"
                       \z}x
                   end

  backtrace.lazy.filter_map do |line|
    match = line.match(backtrace_line)
    next unless match

    T.must(match[:file])
  end
end

.path_from_klass(klass) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/code_ownership/private/file_path_finder.rb', line 12

def self.path_from_klass(klass)
  if klass
    path = Object.const_source_location(klass.to_s)&.first
    (path && Pathname.new(path).relative_path_from(Pathname.pwd).to_s) || nil
  end
rescue NameError
  nil
end