Module: Kernel

Defined in:
lib/lit_pry.rb

Instance Method Summary collapse

Instance Method Details

#require_relative(relative_path) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/lit_pry.rb', line 5

def require_relative relative_path
  filename = relative_path

  # Get directory of the file that called this file.
  absolute_path = caller_locations.first.absolute_path.split('/')
  absolute_path.pop

  # When relative path is current directory.
  if relative_path.start_with?('./')
    filename = relative_path.delete_prefix! './'
  end

  # When relative path is parent directory.
  while relative_path.start_with?('../')
    relative_path.delete_prefix! '../'
    absolute_path.pop
  end

  # Append default extension.
  unless filename.end_with? '.rb'
    filename << '.rb'
  end

  filepath = File.join(absolute_path.join('/'), relative_path)

  # Add pry binding beneath each lit message.
  new_lines = ''
  File.foreach(filepath) do |line|
    new_lines << line
    if line.strip.start_with? 'lit "'
      new_lines << "binding.pry if LitCLI.is_prying?\n"
      new_lines << "@@is_prying = false\n"
    end
  end

  eval(new_lines)
end