Apologies for the poorly worded question title - no idea how to put it better!
In the following code, when I execute ruby bar.rb
, how can I make it output bar.rb
, rather than foo.rb
?
In foo.rb
:
module Foo
def filename
__FILE__
end
end
In bar.rb
:
require_relative 'foo'
include Foo
puts filename # outputs 'foo.rb'
This is for a library function that, each time some code is executed, records the location (and git ref) of that code.
caller
method can get you some of the way there.def filename; file = caller[0].split(':'); file[0]; end
.caller
returns an array of strings, and the first part of each string is what you want. Depending on what you're doing, you may need to consider where in the stack you want to look though. That is, you may not always want the first entry in the array.caller
if you want to find the filename of the caller of the method. Use$0
if you want to find the executable. Usecaller
insidedef self.included
if you want to find the filename when someone includes the module.