class File
Public Class Methods
relative_path( target, reference = Dir.pwd )
click to toggle source
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'
# 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