The Location class is used by Kernel#caller_locations
to store information of
every call frame in a call stack. Instances of this class can store
information such as:
- The path to the file where the frame originated from
- The name of the context of the frame (method name, "block", etc)
- The line number where the frame originated from
In MRI this class can not be initialized from Ruby as it lacks a new
class
method. Implementations that implement this class in Ruby should have a new
class method as the lack of this method is an implementation detail of MRI. For
example, Rubinius does have a new
method like any ordinary Ruby class.
This method returns the full file path of the file the frame originated from:
frame = caller_locations[0]
frame.path.should == __FILE__
If the call frame originated from the main script and the path used to execute said script was relative, then this method returns said relative path. If the path used to execute the main script was absolute then an absolute path is returned. If the call frame originates from a script other than the main script this method always returns the full/absolute path.
For example, create the fixture main.rb
with the following content:
def example
caller_locations[0].path
end
print example
When the script is in the working directory and a relative input path is used:
script = fixture(__FILE__, 'main.rb')
directory = File.dirname(script)
ruby_exe('main.rb', :dir => directory).should == 'main.rb'
When the script is in the working directory and an absolute input path is used:
script = fixture(__FILE__, 'main.rb')
directory = File.dirname(script)
ruby_exe(script, :dir => directory).should == script
When the script is in a sub directory of the working directory and a relative input path is used:
script = 'fixtures/main.rb'
directory = File.dirname(__FILE__)
ruby_exe(script, :dir => directory).should == 'fixtures/main.rb'
When the script is in a sub directory of the working directory and an absolute input path is used:
script = fixture(__FILE__, 'main.rb')
directory = File.dirname(__FILE__)
ruby_exe(script, :dir => directory).should == script