Path  Path::Name

In Files

Parent

  • Object
Generated with Razzle Dazzle Redfish

[Validate]

Name

Path::Name

Path::Name represents a pathname which locates a file in a filesystem. It supports only Unix style pathnames. It does not represent the file itself. A Path::Name can be relative or absolute. It’s not until you try to reference the file that it even matters whether the file exists or not.

Path::Name is immutable. It has no method for destructive update.

The value of this class is to manipulate file path information in a neater way than standard Ruby provides. The examples below demonstrate the difference. All functionality from File, FileTest, and some from Dir and FileUtils is included, in an unsurprising way. It is essentially a facade for all of these, and more.

Examples

Example 1: Using Path::Name

  require 'pathname'
  p = Path::Name.new("/usr/bin/ruby")
  size = p.size              # 27662
  isdir = p.directory?       # false
  dir  = p.dirname           # Path::Name:/usr/bin
  base = p.basename          # Path::Name:ruby
  dir, base = p.split        # [Path::Name:/usr/bin, Path::Name:ruby]
  data = p.read
  p.open { |f| _ }
  p.each_line { |line| _ }

Example 2: Using standard Ruby

  p = "/usr/bin/ruby"
  size = File.size(p)        # 27662
  isdir = File.directory?(p) # false
  dir  = File.dirname(p)     # "/usr/bin"
  base = File.basename(p)    # "ruby"
  dir, base = File.split(p)  # ["/usr/bin", "ruby"]
  data = File.read(p)
  File.open(p) { |f| _ }
  File.foreach(p) { |line| _ }

Example 3: Special features

  p1 = Path::Name.new("/usr/lib")   # Path::Name:/usr/lib
  p2 = p1 + "ruby/1.8"            # Path::Name:/usr/lib/ruby/1.8
  p3 = p1.parent                  # Path::Name:/usr
  p4 = p2.relative_path_from(p3)  # Path::Name:lib/ruby/1.8
  pwd = Path::Name.pwd              # Path::Name:/home/gavin
  pwd.absolute?                   # true
  p5 = Path::Name.new "."           # Path::Name:.
  p5 = p5 + "music/../articles"   # Path::Name:music/../articles
  p5.cleanpath                    # Path::Name:articles
  p5.realpath                     # Path::Name:/home/gavin/articles
  p5.children                     # [Path::Name:/home/gavin/articles/linux, ...]

Breakdown of functionality

Core methods

These methods are effectively manipulating a String, because that’s all a path is. Except for mountpoint?, children, and realpath, they don’t access the filesystem.

File status predicate methods

These methods are a facade for FileTest:

File property and manipulation methods

These methods are a facade for File:

Directory methods

These methods are a facade for Dir:

IO

These methods are a facade for IO:

Utilities

These methods are a mixture of Find, FileUtils, and others:

Method documentation

As the above section shows, most of the methods in Path::Name are facades. The documentation for these methods generally just says, for instance, “See FileTest.writable?“, as you should be familiar with the original method anyway, and its documentation (e.g. through ri) will contain more information. In some cases, a brief description will follow.

Public Class Methods

/(path) click to toggle source

Active path separator.

  p1 = Pathname.new('/')
  p2 = p1 / 'usr' / 'share'   #=> Pathname:/usr/share
# File lib/path/name.rb, line 1094
    def self./(path) #/
      new(path)
    end
[](path) click to toggle source

(Not documented)

# File lib/path/name.rb, line 201
      def [](path)
        new(path)
      end
[](path) click to toggle source

Alternate to Pathname#new.

  Pathname['/usr/share']
# File lib/path/name.rb, line 1085
    def self.[](path)
      new(path)
    end
create( path=[], abs=false, trail=false ) click to toggle source

(Not documented)

# File lib/path/name.rb, line 193
      def create( path=[], abs=false, trail=false )
        o = self.allocate
        o.instance_variable_set("@path", path.dup)
        o.instance_variable_set("@absolute", abs ? true : false)
        o.instance_variable_set("@trail", trail ? true : false)
        o
      end
getwd() click to toggle source

See Dir.getwd. Returns the current working directory as a Path::Name.

# File lib/path/name.rb, line 924
    def self.getwd() Path::Name.new(Dir.getwd) end
glob(*args) click to toggle source

See Dir.glob. Returns or yields Path::Name objects.

# File lib/path/name.rb, line 915
    def self.glob(*args) # :yield: p
      if block_given?
        Dir.glob(*args) {|f| yield Path::Name.new(f) }
      else
        Dir.glob(*args).map {|f| Path::Name.new(f) }
      end
    end
home() click to toggle source

Home constant for building paths from root directory onward.

TODO: Pathname#home needs to be more robust.

# File lib/path/name.rb, line 1107
    def self.home
      self.class.new('~')
    end
new(*path) click to toggle source

Create a Path::Name object from the given String (or String-like object). If path contains a NUL character (0), an ArgumentError is raised.

# File lib/path/name.rb, line 209
    def initialize(*path)
      path = path.join('/')
      @absolute = path[0,1] == '/' ? true : false
      @trail = (path.size > 1 and path[-1,1] == '/') ? true : false
      @path = path.split(%r{/})
      @path.delete('')

      #case path
      #when Path::Name
      #  @path = path.pathlist.dup
      #  @absolute = path.absolute?
      #when Array
      #  @path = path.collect{|e| e.to_str}
      #  @absolute = absolute
      #else
      #  path = path.to_str if path.respond_to?(:to_str)
      #  raise ArgumentError, "pathname contains \\0: #{@path.inspect}" if /\0/ =~ @path
      #  @path = path.split(%r{/})
      #  @path.unshift('') if path[0,1] == '/'  # absolute path
      #end

      self.taint if path.tainted?
    end
null() click to toggle source

Platform dependent null device.

# File lib/path/name.rb, line 1119
    def self.null
      case RUBY_PLATFORM
      when /mswin/i
        'NUL'
      when /amiga/i
        'NIL:'
      when /openvms/i
        'NL:'
      else
        '/dev/null'
      end
    end
root() click to toggle source

Root constant for building paths from root directory onward.

# File lib/path/name.rb, line 1099
    def self.root
      self.class.new('/')
    end
work() click to toggle source

Work constant for building paths from root directory onward.

# File lib/path/name.rb, line 1113
    def self.work
      self.class.new('.')
    end

Public Instance Methods

+(other) click to toggle source

Path::Name#+ appends a pathname fragment to this one to produce a new Path::Name object.

  p1 = Path::Name.new("/usr")      # Path::Name:/usr
  p2 = p1 + "bin/ruby"           # Path::Name:/usr/bin/ruby
  p3 = p1 + "/etc/passwd"        # Path::Name:/etc/passwd

This method doesn’t access the file system; it is pure string manipulation.

# File lib/path/name.rb, line 534
    def +(other)
      path = self.class.new(File.join(to_s, other.to_s))
      path.cleanpath

      #other = Path::Name.new(other) unless Path::Name === other
      #return other if other.absolute?
      #pth = (@path + other.pathlist)
      #pth.delete('.')
      #Path::Name.create(pth, @absolute, other.trail?)

  #    path1 = @path#
  #    path2 = other.to_s
  #    while m2 = %r{\A\.\.(?:/+|\z)}.match(path2) and
  #          m1 = %r{(\A|/+)([^/]+)\z}.match(path1) and
  #          %r{\A(?:\.|\.\.)\z} !~ m1[2]
  #      path1 = m1[1].empty? ? '.' : '/' if (path1 = m1.pre_match).empty?
  #      path2 = '.' if (path2 = m2.post_match).empty?
  #    end
  #    if %r{\A/+\z} =~ path1
  #      while m2 = %r{\A\.\.(?:/+|\z)}.match(path2)
  #        path2 = '.' if (path2 = m2.post_match).empty?
  #      end
  #    end
  #
  #    return Path::Name.new(path2) if path1 == '.'
  #    return Path::Name.new(path1) if path2 == '.'
  #
  #    if %r{/\z} =~ path1
  #      Path::Name.new(path1 + path2)
  #    else
  #      Path::Name.new(path1 + '/' + path2)
  #    end
    end
Also aliased as: /
/(other) click to toggle source

Alias for #+

<<(name) click to toggle source

append directory or file name to path

# File lib/path/name.rb, line 312
    def <<(name)
      name = name.to_str
      @path << name unless name.strip.empty?
      @path
    end
<=>(other) click to toggle source

Provides for comparing pathnames, case-sensitively.

# File lib/path/name.rb, line 269
    def <=>(other)
      return nil unless Path::Name === other
      return 1 if absolute? and not other.absolute?
      return -1 if other.absolute? and not absolute?
      r = @path <=> other.pathlist
      return r unless r == 0
      return 1 if trail? and not other.trail?
      return -1 if other.trail? and not trail?
      0
    end
==(other) click to toggle source

Compare this pathname with other. The comparison is string-based. Be aware that two different paths (foo.txt and ./foo.txt) can refer to the same file.

# File lib/path/name.rb, line 258
    def ==(other)
      return false unless Path::Name === other
      if @absolute
        return false unless other.absolute?
      end
      @path == other.pathlist
    end
Also aliased as: ===, eql?
===(other) click to toggle source

Alias for #==

[](*globs) click to toggle source
# File lib/path/name.rb, line 243
    def [](*globs)
      Path::List.new(self)[*globs]
    end
absolute?() click to toggle source

Predicate method for testing whether a path is absolute. It returns true if the pathname begins with a slash.

# File lib/path/name.rb, line 499
    def absolute?
      #%r{\A/} =~ @path ? true : false
      @absolute
    end
ascend(inclusive=false) click to toggle source

Calls the block for every successive parent directory of the directory path until the root (absolute path) or . (relative path) is reached.

# File lib/path/name.rb, line 688
    def ascend(inclusive=false,&block) # :yield:
      cur_dir = self
      yield( cur_dir.cleanpath ) if inclusive
      until cur_dir.root? or cur_dir == self.class.new(".")
        cur_dir = cur_dir.parent
        yield cur_dir
      end
    end
atime() click to toggle source

See File.atime. Returns last access time.

# File lib/path/name.rb, line 748
    def atime() File.atime(path) end
basename(*args) click to toggle source

See File.basename. Returns the last component of the path.

# File lib/path/name.rb, line 809
    def basename(*args) Path::Name.new(File.basename(path, *args)) end
blockdev?() click to toggle source

See FileTest.blockdev?.

# File lib/path/name.rb, line 843
    def blockdev?() FileTest.blockdev?(path) end
chardev?() click to toggle source

See FileTest.chardev?.

# File lib/path/name.rb, line 846
    def chardev?() FileTest.chardev?(path) end
chdir(&block) click to toggle source

Path::Name#chdir is obsoleted at 1.8.1.

# File lib/path/name.rb, line 928
    def chdir(&block)
      warn "Path::Name#chdir is obsoleted.  Use Dir.chdir."
      Dir.chdir(path, &block)
    end
children(with_directory=true) click to toggle source

Returns the children of the directory (files and subdirectories, not recursive) as an array of Path::Name objects. By default, the returned pathnames will have enough information to access the files. If you set with_directory to false, then the returned pathnames will contain the filename only.

For example:

  p = Path::Name("/usr/lib/ruby/1.8")
  p.children
      # -> [ Path::Name:/usr/lib/ruby/1.8/English.rb,
             Path::Name:/usr/lib/ruby/1.8/Env.rb,
             Path::Name:/usr/lib/ruby/1.8/abbrev.rb, ... ]
  p.children(false)
      # -> [ Path::Name:English.rb, Path::Name:Env.rb, Path::Name:abbrev.rb, ... ]

Note that the result never contain the entries . and .. in the directory because they are not children.

This method has existed since 1.8.1.

# File lib/path/name.rb, line 614
    def children(with_directory=true)
      with_directory = false if @path == ['.']
      result = []
      Dir.foreach(to_s) {|e|
        next if e == '.' || e == '..'
        if with_directory
          result << Path::Name.create(@path + [e], absolute?)
        else
          result << Path::Name.new(e)
        end
      }
      result
    end
chmod(mode) click to toggle source

See File.chmod. Changes permissions.

# File lib/path/name.rb, line 757
    def chmod(mode) File.chmod(mode, path) end
chown(owner, group) click to toggle source

See File.chown. Change owner and group of file.

# File lib/path/name.rb, line 763
    def chown(owner, group) File.chown(owner, group, path) end
chroot() click to toggle source

Path::Name#chroot is obsoleted at 1.8.1.

# File lib/path/name.rb, line 934
    def chroot
      warn "Path::Name#chroot is obsoleted.  Use Dir.chroot."
      Dir.chroot(path)
    end
cleanpath(consider_symlink=false) click to toggle source

Returns clean pathname of self with consecutive slashes and useless dots removed. The filesystem is not accessed.

If consider_symlink is true, then a more conservative algorithm is used to avoid breaking symbolic linkages. This may retain more .. entries than absolutely necessary, but without accessing the filesystem, this can’t be avoided. See realpath.

# File lib/path/name.rb, line 327
    def cleanpath(consider_symlink=false)
      if consider_symlink
        cleanpath_conservative
      else
        cleanpath_aggressive
      end
    end
ctime() click to toggle source

See File.ctime. Returns last (directory entry, not file) change time.

# File lib/path/name.rb, line 751
    def ctime() File.ctime(path) end
current?() click to toggle source

(Not documented)

# File lib/path/name.rb, line 492
    def current?
      #%r{\A/+\z} =~ @path ? true : false
      (!@absolute) and @path.empty?
    end
delete() click to toggle source

Alias for unlink

descend() click to toggle source

Calls the block for every successive subdirectory of the directory path from the root (absolute path) until . (relative path) is reached.

# File lib/path/name.rb, line 700
    def descend()
      @path.scan(%r{[^/]*/?})[0...-1].inject('') do |path, dir|
        yield self.class.new(path << dir)
        path
      end
    end
dir?() click to toggle source

Like directory? but return self if true, otherwise nil.

# File lib/path/name.rb, line 864
    def dir? ; directory? ? self : nil ; end
dir_foreach(*args, &block) click to toggle source

Path::Name#dir_foreach is obsoleted at 1.8.1.

# File lib/path/name.rb, line 952
    def dir_foreach(*args, &block)
      warn "Path::Name#dir_foreach is obsoleted.  Use Path::Name#each_entry."
      each_entry(*args, &block)
    end
directory?() click to toggle source

See FileTest.directory?.

# File lib/path/name.rb, line 861
    def directory?() FileTest.directory?(path) end
dirname() click to toggle source

See File.dirname. Returns all but the last component of the path.

# File lib/path/name.rb, line 812
    def dirname() Path::Name.new(File.dirname(path)) end
each_entry() click to toggle source

Iterates over the entries (files and subdirectories) in the directory. It yields a Path::Name object for each entry.

This method has existed since 1.8.1.

# File lib/path/name.rb, line 947
    def each_entry(&block) # :yield: p
      Dir.foreach(path) {|f| yield Path::Name.new(f) }
    end
each_filename() click to toggle source

Iterates over each component of the path.

  Path::Name.new("/usr/bin/ruby").each_filename {|filename| ... }
    # yields "usr", "bin", and "ruby".
# File lib/path/name.rb, line 519
    def each_filename # :yield: e
      #@path.scan(%r{[^/]+}) { yield $& }
      @path.each { |e| yield e }
    end
each_line(*args) click to toggle source

each_line iterates over the line in the file. It yields a String object for each line.

This method has existed since 1.8.1.

# File lib/path/name.rb, line 723
    def each_line(*args, &block) # :yield: line
      IO.foreach(path, *args, &block)
    end
empty?() click to toggle source
# File lib/path/name.rb, line 996
    def empty?
      Dir.glob(::File.join(self.to_s, '*')).empty?
    end
entries() click to toggle source

Return the entries (files and subdirectories) in the directory, each as a Path::Name object.

# File lib/path/name.rb, line 941
    def entries() Dir.entries(path).map {|f| Path::Name.new(f) } end
eql?(other) click to toggle source

Alias for #==

executable?() click to toggle source

See FileTest.executable?.

# File lib/path/name.rb, line 849
    def executable?() FileTest.executable?(path) end
executable_real?() click to toggle source

See FileTest.executable_real?.

# File lib/path/name.rb, line 852
    def executable_real?() FileTest.executable_real?(path) end
exist?() click to toggle source

See FileTest.exist?.

# File lib/path/name.rb, line 855
    def exist?() FileTest.exist?(path) end
expand_path(*args) click to toggle source

See File.expand_path.

# File lib/path/name.rb, line 818
    def expand_path(*args) Path::Name.new(File.expand_path(path, *args)) end
extname() click to toggle source

See File.extname. Returns the file’s extension.

# File lib/path/name.rb, line 815
    def extname() File.extname(path) end
file?() click to toggle source

See FileTest.file?.

# File lib/path/name.rb, line 867
    def file?() FileTest.file?(path) end
find() click to toggle source

Path::Name#find is an iterator to traverse a directory tree in a depth first manner. It yields a Path::Name for each file under “this” directory.

Since it is implemented by find.rb, Find.prune can be used to control the traverse.

If self is ., yielded pathnames begin with a filename in the current directory, not ./.

# File lib/path/name.rb, line 1013
    def find(&block) # :yield: p
      require 'find'
      if @path == ['.']
        Find.find(path) {|f| yield Path::Name.new(f.sub(%r{\A\./}, '')) }
      else
        Find.find(path) {|f| yield Path::Name.new(f) }
      end
    end
fnmatch(pattern, *args) click to toggle source

See File.fnmatch. Return true if the receiver matches the given pattern.

# File lib/path/name.rb, line 770
    def fnmatch(pattern, *args) File.fnmatch(pattern, path, *args) end
fnmatch?(pattern, *args) click to toggle source

See File.fnmatch? (same as fnmatch).

# File lib/path/name.rb, line 773
    def fnmatch?(pattern, *args) File.fnmatch?(pattern, path, *args) end
foreach(*args, &block) click to toggle source

This method is obsoleted at 1.8.1. Use each_line or each_entry.

# File lib/path/name.rb, line 1067
    def foreach(*args, &block)
      warn "Path::Name#foreach is obsoleted.  Use each_line or each_entry."
      if FileTest.directory? path
        # For polymorphism between Dir.foreach and IO.foreach,
        # Path::Name#foreach doesn't yield Path::Name object.
        Dir.foreach(path, *args, &block)
      else
        IO.foreach(path, *args, &block)
      end
    end
foreachline(*args, &block) click to toggle source

Path::Name#foreachline is obsoleted at 1.8.1. Use each_line.

# File lib/path/name.rb, line 728
    def foreachline(*args, &block)
      warn "Path::Name#foreachline is obsoleted.  Use Path::Name#each_line."
      each_line(*args, &block)
    end
freeze() click to toggle source

(Not documented)

# File lib/path/name.rb, line 233
    def freeze()  super ; @path.freeze  ; self end
ftype() click to toggle source

See File.ftype. Returns “type” of file (“file”, “directory”, etc).

# File lib/path/name.rb, line 777
    def ftype() File.ftype(path) end
glob(match, *opts) click to toggle source
# File lib/path/name.rb, line 969
    def glob(match, *opts)
      flags = 0
      opts.each do |opt|
        case opt when Symbol, String
          flags += ::File.const_get("FNM_#{opt}".upcase)
        else
          flags += opt
        end
      end
      Dir.glob(::File.join(self.to_s, match), flags).collect{ |m| self.class.new(m) }
    end
glob_first(match, *opts) click to toggle source
# File lib/path/name.rb, line 982
    def glob_first(match, *opts)
      flags = 0
      opts.each do |opt|
        case opt when Symbol, String
          flags += ::File.const_get("FNM_#{opt}".upcase)
        else
          flags += opt
        end
      end
      file = ::Dir.glob(::File.join(self.to_s, match), flags).first
      file ? self.class.new(file) : nil
    end
grpowned?() click to toggle source

See FileTest.grpowned?.

# File lib/path/name.rb, line 858
    def grpowned?() FileTest.grpowned?(path) end
join(*args) click to toggle source

Path::Name#join joins pathnames.

path0.join(path1, ..., pathN) is the same as path0 + path1 + ... + pathN.

HELP ME!!!

# File lib/path/name.rb, line 579
    def join(*args)
      Path::Name.new(*args)
      #args.unshift self
      #result = args.pop
      #result = Path::Name.new(result) unless Path::Name === result
      #return result if result.absolute?
      #args.reverse_each {|arg|
      #  arg = Path::Name.new(arg) unless Path::Name === arg
      #  result = arg + result
      #  return result if result.absolute?
      #}
      #result
    end
lchmod(mode) click to toggle source

See File.lchmod.

# File lib/path/name.rb, line 760
    def lchmod(mode) File.lchmod(mode, path) end
lchown(owner, group) click to toggle source

See File.lchown.

# File lib/path/name.rb, line 766
    def lchown(owner, group) File.lchown(owner, group, path) end
lstat() click to toggle source

See File.lstat.

# File lib/path/name.rb, line 797
    def lstat() File.lstat(path) end
mkdir(*args) click to toggle source

See Dir.mkdir. Create the referenced directory.

# File lib/path/name.rb, line 958
    def mkdir(*args) Dir.mkdir(path, *args) end
mkpath() click to toggle source

See FileUtils.mkpath. Creates a full path, including any intermediate directories that don’t yet exist.

# File lib/path/name.rb, line 1027
    def mkpath
      require 'fileutils'
      FileUtils.mkpath(path)
      nil
    end
mountpoint?() click to toggle source

mountpoint? returns true if self points to a mountpoint.

# File lib/path/name.rb, line 469
    def mountpoint?
      begin
        stat1 = self.lstat
        stat2 = self.parent.lstat
        stat1.dev == stat2.dev && stat1.ino == stat2.ino ||
          stat1.dev != stat2.dev
      rescue Errno::ENOENT
        false
      end
    end
mtime() click to toggle source

See File.mtime. Returns last modification time.

# File lib/path/name.rb, line 754
    def mtime() File.mtime(path) end
open(*args) click to toggle source

See File.open. Opens the file for reading or writing.

# File lib/path/name.rb, line 783
    def open(*args, &block) # :yield: file
      File.open(path, *args, &block)
    end
opendir() click to toggle source

See Dir.open.

# File lib/path/name.rb, line 964
    def opendir(&block) # :yield: dir
      Dir.open(path, &block)
    end
outofdate?(*sources) click to toggle source
# File lib/path/name.rb, line 1048
    def outofdate?(*sources)
      ! uptodate?(*sources)
    end
owned?() click to toggle source

See FileTest.owned?.

# File lib/path/name.rb, line 876
    def owned?() FileTest.owned?(path) end
parent() click to toggle source

parent returns the parent directory.

This is same as self + '..'.

# File lib/path/name.rb, line 464
    def parent
      self << '..'
    end
path() click to toggle source

Return the path as a String (same as to_s).

# File lib/path/name.rb, line 285
    def path
      s = ''
      s << '/' if @absolute
      s << @path.join('/')
      s << '/' if @trail
      s << '.' if s.empty?
      s
    end
pathlist() click to toggle source

Stores the array of the componet parts of the pathname.

protected

# File lib/path/name.rb, line 250
    def pathlist
      @path
    end
pipe?() click to toggle source

See FileTest.pipe?.

# File lib/path/name.rb, line 870
    def pipe?() FileTest.pipe?(path) end
read(*args) click to toggle source

See IO.read. Returns all the bytes from the file, or the first N if specified.

# File lib/path/name.rb, line 735
    def read(*args) IO.read(path, *args) end
readable?() click to toggle source

See FileTest.readable?.

# File lib/path/name.rb, line 879
    def readable?() FileTest.readable?(path) end
readable_real?() click to toggle source

See FileTest.readable_real?.

# File lib/path/name.rb, line 882
    def readable_real?() FileTest.readable_real?(path) end
readlines(*args) click to toggle source

See IO.readlines. Returns all the lines from the file.

# File lib/path/name.rb, line 738
    def readlines(*args) IO.readlines(path, *args) end
realpath(*args) click to toggle source

Returns a real (absolute) pathname of self in the actual filesystem. The real pathname doesn’t contain symlinks or useless dots.

No arguments should be given; the old behaviour is obsoleted.

# File lib/path/name.rb, line 396
    def realpath(*args)
      unless args.empty?
        warn "The argument for Path::Name#realpath is obsoleted."
      end
      force_absolute = args.fetch(0, true)

      if @path.first == ''
        top = '/'
        unresolved = @path.slice(1..-1) #.scan(%r{[^/]+})
      elsif force_absolute
        # Although POSIX getcwd returns a pathname which contains no symlink,
        # 4.4BSD-Lite2 derived getcwd may return the environment variable $PWD
        # which may contain a symlink.
        # So the return value of Dir.pwd should be examined.
        top = '/'
        unresolved = Dir.pwd.split(%r{/}) + @path
      else
        top = ''
        unresolved = @path.dup #.scan(%r{[^/]+})
      end
      resolved = []

      until unresolved.empty?
        case unresolved.last
        when '.'
          unresolved.pop
        when '..'
          resolved.unshift unresolved.pop
        else
          loop_check = {}
          while (stat = File.lstat(path = top + unresolved.join('/'))).symlink?
            symlink_id = "#{stat.dev}:#{stat.ino}"
            raise Errno::ELOOP.new(path) if loop_check[symlink_id]
            loop_check[symlink_id] = true
            if %r{\A/} =~ (link = File.readlink(path))
              top = '/'
              unresolved = link.split(%r{/}) #scan(%r{[^/]+})
            else
              unresolved[-1,1] = link.split(%r{/}) #.scan(%r{[^/]+})
            end
          end
          next if (filename = unresolved.pop) == '.'
          if filename != '..' && resolved.first == '..'
            resolved.shift
          else
            resolved.unshift filename
          end
        end
      end

      if top == '/'
        resolved.shift while resolved[0] == '..'
      end

      if resolved.empty?
        Path::Name.new(top.empty? ? '.' : '/')
      else
        if top.empty?
          Path::Name.new(resolved)
        else
          Path::Name.new(resolved, true)
        end
      end
    end
relative?() click to toggle source

The opposite of absolute?

# File lib/path/name.rb, line 505
    def relative?
      !@absolute
    end
relative_path_from(base_directory) click to toggle source

relative_path_from returns a relative path from the argument to the receiver. If self is absolute, the argument must be absolute too. If self is relative, the argument must be relative too.

relative_path_from doesn’t access the filesystem. It assumes no symlinks.

ArgumentError is raised when it cannot find a relative path.

This method has existed since 1.8.1.

# File lib/path/name.rb, line 639
    def relative_path_from(base_directory)
      if self.absolute? != base_directory.absolute?
        raise ArgumentError,
          "relative path between absolute and relative path: #{self.inspect}, #{base_directory.inspect}"
      end

      dest = []
      self.cleanpath.each_filename {|f|
        next if f == '.'
        dest << f
      }

      base = []
      base_directory.cleanpath.each_filename {|f|
        next if f == '.'
        base << f
      }

      while !base.empty? && !dest.empty? && base[0] == dest[0]
        base.shift
        dest.shift
      end

      if base.include? '..'
        raise ArgumentError, "base_directory has ..: #{base_directory.inspect}"
      end

      base.fill '..'
      relpath = base + dest
      if relpath.empty?
        Path::Name.new('.')
      else
        Path::Name.create(relpath, false) #.join('/'))
      end
    end
rename(to) click to toggle source

See File.rename. Rename the file.

# File lib/path/name.rb, line 791
    def rename(to) File.rename(path, to) end
rmdir() click to toggle source

See Dir.rmdir. Remove the referenced directory.

# File lib/path/name.rb, line 961
    def rmdir() Dir.rmdir(path) end
rmtree() click to toggle source

See FileUtils.rm_r. Deletes a directory and all beneath it.

# File lib/path/name.rb, line 1034
    def rmtree
      # The name "rmtree" is borrowed from File::Path of Perl.
      # File::Path provides "mkpath" and "rmtree".
      require 'fileutils'
      FileUtils.rm_r(path)
      nil
    end
root?() click to toggle source

root? is a predicate for root directories. I.e. it returns true if the pathname consists of consecutive slashes.

It doesn’t access actual filesystem. So it may return false for some pathnames which points to roots such as /usr/...

# File lib/path/name.rb, line 487
    def root?
      #%r{\A/+\z} =~ @path ? true : false
      @absolute and @path.empty?
    end
rootname() click to toggle source
# File lib/path/name.rb, line 676
    def rootname
      # this should be fairly robust
      path_re = Regexp.new('[' + Regexp.escape(File::Separator + %q{\/}) + ']')
      head, tail = path.split(path_re, 2)
      return '.' if path == head
      return '/' if head.empty?
      self.class.new(head)
    end
setgid?() click to toggle source

See FileTest.setgid?.

# File lib/path/name.rb, line 888
    def setgid?() FileTest.setgid?(path) end
setuid?() click to toggle source

See FileTest.setuid?.

# File lib/path/name.rb, line 885
    def setuid?() FileTest.setuid?(path) end
size() click to toggle source

See FileTest.size.

# File lib/path/name.rb, line 891
    def size() FileTest.size(path) end
size?() click to toggle source

See FileTest.size?.

# File lib/path/name.rb, line 894
    def size?() FileTest.size?(path) end
socket?() click to toggle source

See FileTest.socket?.

# File lib/path/name.rb, line 873
    def socket?() FileTest.socket?(path) end
split() click to toggle source

See File.split. Returns the dirname and the basename in an Array.

# File lib/path/name.rb, line 822
    def split() File.split(path).map {|f| Path::Name.new(f) } end
split_root() click to toggle source
# File lib/path/name.rb, line 708
    def split_root
      path_re = Regexp.new('[' + Regexp.escape(File::Separator + %q{\/}) + ']')
      head, tail = *path.split(path_re, 2)
      [self.class.new(head), self.class.new(tail)]
    end
stat() click to toggle source

See File.stat. Returns a File::Stat object.

# File lib/path/name.rb, line 794
    def stat() File.stat(path) end
sticky?() click to toggle source

See FileTest.sticky?.

# File lib/path/name.rb, line 897
    def sticky?() FileTest.sticky?(path) end
sysopen(*args) click to toggle source

See IO.sysopen.

# File lib/path/name.rb, line 741
    def sysopen(*args) IO.sysopen(path, *args) end
taint() click to toggle source

(Not documented)

# File lib/path/name.rb, line 234
    def taint()   super ; @path.taint   ; self end
to_path() click to toggle source

Convertion method for path names. This returns self.

# File lib/path/name.rb, line 238
    def to_path
      self
    end
to_s() click to toggle source

Return the path as a String (same as pathname).

# File lib/path/name.rb, line 295
    def to_s
      s = ''
      s << '/' if @absolute
      s << @path.join('/')
      s << '/' if @trail
      s << '.' if s.empty?
      s
    end
Also aliased as: to_str
to_str() click to toggle source

Alias for to_s

trail?() click to toggle source

(Not documented)

# File lib/path/name.rb, line 509
    def trail?
      @trail
    end
truncate(length) click to toggle source

See File.truncate. Truncate the file to length bytes.

# File lib/path/name.rb, line 803
    def truncate(length) File.truncate(path, length) end
untaint() click to toggle source

(Not documented)

# File lib/path/name.rb, line 235
    def untaint() super ; @path.untaint ; self end
uptodate?(*sources) click to toggle source
# File lib/path/name.rb, line 1043
    def uptodate?(*sources)
      ::FileUtils.uptodate?(to_s, sources.flatten)
    end
utime(atime, mtime) click to toggle source

See File.utime. Update the access and modification times.

# File lib/path/name.rb, line 806
    def utime(atime, mtime) File.utime(atime, mtime, path) end
writable?() click to toggle source

See FileTest.writable?.

# File lib/path/name.rb, line 903
    def writable?() FileTest.writable?(path) end
writable_real?() click to toggle source

See FileTest.writable_real?.

# File lib/path/name.rb, line 906
    def writable_real?() FileTest.writable_real?(path) end
zero?() click to toggle source

See FileTest.zero?.

# File lib/path/name.rb, line 909
    def zero?() FileTest.zero?(path) end

Private Instance Methods

cleanpath_aggressive() click to toggle source

Clean the path simply by resolving and removing excess “.” and “..” entries. Nothing more, nothing less.

# File lib/path/name.rb, line 338
    def cleanpath_aggressive
      # cleanpath_aggressive assumes:
      # * no symlink
      # * all pathname prefix contained in the pathname is existing directory
      return Path::Name.create([],@absolute,@trail) if path.empty?
      absolute = absolute?
      trail = trail?
      names = []
      @path.each {|name|
        next if name == '.'
        if name == '..'
          if names.empty?
            next if absolute
          else
            if names.last != '..'
              names.pop
              next
            end
          end
        end
        names << name
      }
      return Path::Name.new(absolute ? '/' : '.') if names.empty?
      #path = []
      #path << '' if absolute
      #path.concat(names)
      Path::Name.create(names, absolute) #, trail)
    end
cleanpath_conservative() click to toggle source

(Not documented)

# File lib/path/name.rb, line 368
    def cleanpath_conservative
      return Path::Name.create([],@absolute) if @path.empty?
      names = @path.dup #.scan(%r{[^/]+})
      last_dot = (names.last == '.')
      names.delete('.')
      names.shift while names.first == '..' if absolute?
      return Path::Name.new(absolute? ? '/' : '.') if names.empty?
      newpath = []
      trail = false
      #newpath << '' if absolute?
      newpath.concat(names)
      if names.last != '..'
        if last_dot
          newpath << '.'
        elsif trail? #%r{/\z} =~ @path  #HOW TO DEAL WITH TRAILING '/' ?
          trail = true
        end
      end
      Path::Name.create(newpath, absolute?, trail)
    end

Disabled; run with --debug to generate this.