luckyme
luckyme

Reputation: 21

Find path to file that required this one

I'll show an example of what I'm trying to do.

child.rb

require 'parent'
class Child < Parent
  ...
end

parent.rb

class Parent 
  puts __FILE__
  ...
end

running this (e.g. in IRB):

require 'child'
child=Child.new

returns this:

/path/to/parent.rb

but i'm really trying to get the file child.rb instead.

How can i do this without moving the puts __FILE__ in to the child class directly?

Upvotes: 1

Views: 34

Answers (3)

Daniel Loureiro
Daniel Loureiro

Reputation: 5323

you can use some backtrace method like caller_locations(1,1)[0].path or caller

Upvotes: 0

sawa
sawa

Reputation: 168081

Redefine require to output caller_locations.first.absolute_path before calling the original require.

Upvotes: 0

Phrogz
Phrogz

Reputation: 303205

There is no way in Ruby to get what you are asking for. Perhaps if you explained why you want this—what you are trying to accomplish—then I (or someone else) could help you further. As it stands you seem to be asking an XY problem.

Although it's not always the "file that required me", you can use $0 in this case instead of __FILE__ to get "the root file that is running" in the case when you have done ruby parent.rb. Note that this will not work with IRB, however. (Inside IRB $0 is always "irb" or something equally unhelpful.)

Upvotes: 1

Related Questions