Class: File

Inherits:
Object
  • Object
show all
Defined in:
lib/antlr3/test/core-extensions.rb

Class Method Summary collapse

Class Method Details

.relative_path(target, reference = Dir.pwd) ⇒ Object

given some target path string, and an optional reference path (Dir.pwd by default), this method returns a string containing the relative path of the target path from the reference path

Examples:

File.relative_path('rel/path')   # => './rel/path'
File.relative_path('/some/abs/path', '/some')  # => './abs/path'
File.relative_path('/some/file.txt', '/some/abs/path')  # => '../../file.txt'

187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/antlr3/test/core-extensions.rb', line 187

def self.relative_path( target, reference = Dir.pwd )
  pair = [ target, reference ].map! do |path|
    File.expand_path( path.to_s ).split( File::Separator ).tap do |list|
      if list.empty? then list << String.new( File::Separator )
      elsif list.first.empty? then list.first.replace( File::Separator )
      end
    end
  end

  target_list, reference_list = pair
  while target_list.first == reference_list.first
    target_list.shift
    reference_list.shift or break
  end
  
  relative_list = Array.new( reference_list.length, '..' )
  relative_list.empty? and relative_list << '.'
  relative_list.concat( target_list ).compact!
  return relative_list.join( File::Separator )
end