Get path to parent file, Ruby

Is it possible to get the location of a file that requires another file in Ruby?

I have a project in which I start some processes, and I would like to be able to determine in the code which file is the parent of the required file. This is good for debugging.

Example:

#initial.rb:
require "./my_file.rb"
fork do
   require "./my_file2.rb"
end

-

#my_file.rb:

puts "Required from file: #{?????}"

-

#my_file2.rb:

require "./my_file.rb"

I would expect to get something like:

#=> Required from file: /path/to/initial.rb
#=> Required from file: /path/to/my_file2.rb
+4
source share
2 answers

Based on Jacob's answer , I ended this redefinition require_relativeand require:

alias :old_require_relative :require_relative
def require_relative(arg)
  #~ puts caller.map{|x| "\t#{x}"}
  puts "%s requires %s" % [ caller.first.split(/:\d+/,2).first, arg]
  old_require_relative arg
end
alias :old_require :require
def require(arg)
  #~ puts caller.map{|x| "\t#{x}"}
  puts "%s requires %s" % [ caller.first.split(/:\d+/,2).first, arg]
  old_require arg
end

In a test test case with the following boot sequence:

test.rb
+-  test1.rb
    +- test1_a.rb
+ test2.rb

Next calls

require './test1'
require './test2'

or

require_relative 'test1'
require_relative 'test2'

lead to:

test.rb requires ./test1
C:/Temp/test1.rb requires test1_a
test.rb requires ./test2

You can also include an output string in the output.

+2
source

, Kernel#caller. ( , ).

+1

Source: https://habr.com/ru/post/1537510/


All Articles