Class: File

Inherits:
Object
  • Object
show all
Defined in:
lib/relative/file.rb

Constant Summary collapse

RELATIVE_GEM_SOURCE_DIR =

Compute this information (the directory containing the relative gem’s source code) when this file is loaded; this information is used within File#expand_path_relative_to_caller.

File.expand_path(File.dirname(__FILE__))

Class Method Summary collapse

Class Method Details

.expand_path_relative_to_caller(file_name) ⇒ Object

Description:

This method returns an absolute expansion of file_name, relative to the caller’s source file. Note that this method is a no-op if file_name is absolute.

Examples:

If the caller’s source file is:

/usr/bin/scripts/print_file.rb

then

File.expand_path_relative_to_caller("config/print_file.cfg")

will return

"/usr/bin/scripts/config/print_file.cfg"

Parameters:

file_name

A file system path relative to the calling file

Returns:

An absolute expansion of file_name, relative to the caller’s source file.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/relative/file.rb', line 30

def self.expand_path_relative_to_caller(file_name)
  caller_stack = caller(1) # Start the call stack at the caller
  external_caller_file_dir = caller_stack.each do |caller_stack_frame|
    caller_file_name = caller_stack_frame.split(":")[0]
    caller_file_dir = File.expand_path(File.dirname(caller_file_name))
    
    #
    # Treat callers inside the relative gem differently from those
    # outside the relative gem.  In particular, assume that
    # callers within the relative gem want paths expanded relative
    # to *their* callers.
    #
    if(caller_file_dir != RELATIVE_GEM_SOURCE_DIR)
      break caller_file_dir
    end
  end
  
  return File.expand_path(file_name, external_caller_file_dir)
end