123456789_123456789_123456789_123456789_123456789_

Class: Pathname

Overview

Pathname represents the name of a file or directory on the filesystem, but not the file itself.

The pathname depends on the Operating System: Unix, Windows, etc. This library works with pathnames of local OS, however non-Unix pathnames are supported experimentally.

A Pathname 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.

Pathname is immutable. It has no method for destructive update.

The goal 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 Pathname

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

Example 2: Using standard Ruby

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

Example 3: Special features

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

Breakdown of functionality

Core methods

These methods are effectively manipulating a String, because that's all a path is. None of these access the file system except for #mountpoint?, #children, #each_child, #realdirpath and #realpath.

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:

  • #each_line(*args, &block)

  • #read(*args)

  • #binread(*args)

  • #readlines(*args)

  • #sysopen(*args)

Utilities

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

Method documentation

As the above section shows, most of the methods in Pathname 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.

Class Method Summary

  • .getwd

    Alias for .pwd.

  • .glob(*args)

    Returns or yields Pathname objects.

  • .new(arg) constructor

    Create a Pathname object from the given String (or String-like object).

  • .pwd (also: .getwd)

    Returns the current working directory as a Pathname.

Instance Attribute Summary

Instance Method Summary

Constructor Details

.new(arg)

Create a Pathname object from the given String (or String-like object). If path contains a NULL character (\0), an ArgumentError is raised.

Class Method Details

.getwd

Alias for .pwd.

.glob(*args)

Returns or yields Pathname objects.

Pathname.glob("config/" "*.rb")
    #=> [#<Pathname:config/environment.rb>, #<Pathname:config/routes.rb>, ..]

See Dir.glob.

.pwd Also known as: .getwd

Returns the current working directory as a Pathname.

Pathname.getwd
    #=> #<Pathname:/home/zzak/projects/ruby>

See Dir.getwd.

Instance Attribute Details

#absolute?Boolean (readonly)

Predicate method for testing whether a path is absolute.

It returns true if the pathname begins with a slash.

p = Pathname.new('/im/sure')
p.absolute?
    #=> true

p = Pathname.new('not/so/sure')
p.absolute?
    #=> false
[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 227

def absolute?
  !relative?
end

#blockdev?Boolean (readonly)

See FileTest.blockdev?.

#chardev?Boolean (readonly)

See FileTest.chardev?.

#directory?Boolean (readonly)

See FileTest.directory?.

#executable?Boolean (readonly)

See FileTest.executable?.

#executable_real?Boolean (readonly)

See FileTest.executable_real?.

#exist?Boolean (readonly)

See FileTest.exist?.

#file?Boolean (readonly)

See FileTest.file?.

#grpowned?Boolean (readonly)

See FileTest.grpowned?.

#mountpoint?Boolean (readonly)

Returns true if self points to a mountpoint.

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 194

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

#owned?Boolean (readonly)

See FileTest.owned?.

#pipe?Boolean (readonly)

See FileTest.pipe?.

#readable?Boolean (readonly)

See FileTest.readable?.

#readable_real?Boolean (readonly)

See FileTest.readable_real?.

#relative?Boolean (readonly)

The opposite of #absolute?

It returns false if the pathname begins with a slash.

p = Pathname.new('/im/sure')
p.relative?
    #=> false

p = Pathname.new('not/so/sure')
p.relative?
    #=> true
[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 242

def relative?
  path = @path
  while r = chop_basename(path)
    path, = r
  end
  path == ''
end

#root?Boolean (readonly)

Predicate method for root directories. Returns true if the pathname consists of consecutive slashes.

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

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 212

def root?
  !!(chop_basename(@path) == nil && /#{SEPARATOR_PAT}/o =~ @path)
end

#setgid?Boolean (readonly)

See FileTest.setgid?.

#setuid?Boolean (readonly)

See FileTest.setuid?.

#size (readonly)

See FileTest.size.

#size?Boolean (readonly)

See FileTest.size?.

#socket?Boolean (readonly)

See FileTest.socket?.

#sticky?Boolean (readonly)

See FileTest.sticky?.

#symlink?Boolean (readonly)

See FileTest.symlink?.

#world_readable?Boolean (readonly)

See FileTest.world_readable?.

#world_writable?Boolean (readonly)

See FileTest.world_writable?.

#writable?Boolean (readonly)

See FileTest.writable?.

#writable_real?Boolean (readonly)

See FileTest.writable_real?.

#zero?Boolean (readonly)

See FileTest.zero?.

Instance Method Details

#+(other) Also known as: #/

Appends a pathname fragment to self to produce a new Pathname object.

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

# / is aliased to +.
p4 = p1 / "bin/ruby"           # Pathname:/usr/bin/ruby
p5 = p1 / "/etc/passwd"        # Pathname:/etc/passwd

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

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 336

def +(other)
  other = Pathname.new(other) unless Pathname === other
  Pathname.new(plus(@path, other.to_s))
end

#/(other)

Alias for #+.

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 340

alias / +

#<=>(other)

Provides a case-sensitive comparison operator for pathnames.

Pathname.new('/usr') <=> Pathname.new('/usr/bin')
    #=> -1
Pathname.new('/usr/bin') <=> Pathname.new('/usr/bin')
    #=> 0
Pathname.new('/usr/bin') <=> Pathname.new('/USR/BIN')
    #=> 1

It will return -1, 0 or 1 depending on the value of the left argument relative to the right argument. Or it will return nil if the arguments are not comparable.

#==(other) Also known as: #===, #eql?

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.

#===(other)

Alias for #==.

#ascend {|_self| ... }

Iterates over and yields a new Pathname object for each element in the given path in ascending order.

Pathname.new('/path/to/some/file.rb').ascend {|v| p v}
   #<Pathname:/path/to/some/file.rb>
   #<Pathname:/path/to/some>
   #<Pathname:/path/to>
   #<Pathname:/path>
   #<Pathname:/>

Pathname.new('path/to/some/file.rb').ascend {|v| p v}
   #<Pathname:path/to/some/file.rb>
   #<Pathname:path/to/some>
   #<Pathname:path/to>
   #<Pathname:path>

It doesn't access the filesystem.

Yields:

  • (_self)

Yield Parameters:

  • _self (Pathname)

    the object that the method was called on

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 313

def ascend
  path = @path
  yield self
  while r = chop_basename(path)
    path, = r
    break if path.empty?
    yield self.class.new(del_trailing_separator(path))
  end
end

#atimeTime

Returns the last access time for the file.

See File.atime.

#basename(*args)

Returns the last component of the path.

See File.basename.

#binread([length [, offset]]) ⇒ String

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

See IO.binread.

#binwrite(string, [offset]) ⇒ Fixnum #binwrite(string, [offset], open_args) ⇒ Fixnum

Writes contents to the file, opening it in binary mode.

See IO.binwrite.

#birthtimeTime

Returns the birth time for the file. If the platform doesn't have birthtime, returns ctime.

See File.birthtime.

#children(with_directory = true)

Returns the children of the directory (files and subdirectories, not recursive) as an array of Pathname 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:

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

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

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 427

def children(with_directory=true)
  with_directory = false if @path == '.'
  result = []
  Dir.foreach(@path) {|e|
    next if e == '.' || e == '..'
    if with_directory
      result << self.class.new(File.join(@path, e))
    else
      result << self.class.new(e)
    end
  }
  result
end

#chmodInteger

Changes file permissions.

See File.chmod.

#chownInteger

Change owner and group of the file.

See File.chown.

#cleanpath(consider_symlink = false)

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.

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 87

def cleanpath(consider_symlink=false)
  if consider_symlink
    cleanpath_conservative
  else
    cleanpath_aggressive
  end
end

#ctimeTime

Returns the last change time, using directory information, not the file itself.

See File.ctime.

#delete Also known as: #unlink

Removes a file or directory, using File.unlink if self is a file, or Dir.unlink as necessary.

#descend

Iterates over and yields a new Pathname object for each element in the given path in descending order.

Pathname.new('/path/to/some/file.rb').descend {|v| p v}
   #<Pathname:/>
   #<Pathname:/path>
   #<Pathname:/path/to>
   #<Pathname:/path/to/some>
   #<Pathname:/path/to/some/file.rb>

Pathname.new('path/to/some/file.rb').descend {|v| p v}
   #<Pathname:path>
   #<Pathname:path/to>
   #<Pathname:path/to/some>
   #<Pathname:path/to/some/file.rb>

It doesn't access the filesystem.

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 288

def descend
  vs = []
  ascend {|v| vs << v }
  vs.reverse_each {|v| yield v }
  nil
end

#dirname

Returns all but the last component of the path.

See File.dirname.

#each_child(with_directory = true, &b)

Iterates over the children of the directory (files and subdirectories, not recursive).

It yields Pathname object for each child.

By default, the yielded 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.

Pathname("/usr/local").each_child {|f| p f }
#=> #<Pathname:/usr/local/share>
#   #<Pathname:/usr/local/bin>
#   #<Pathname:/usr/local/games>
#   #<Pathname:/usr/local/lib>
#   #<Pathname:/usr/local/include>
#   #<Pathname:/usr/local/sbin>
#   #<Pathname:/usr/local/src>
#   #<Pathname:/usr/local/man>

Pathname("/usr/local").each_child(false) {|f| p f }
#=> #<Pathname:share>
#   #<Pathname:bin>
#   #<Pathname:games>
#   #<Pathname:lib>
#   #<Pathname:include>
#   #<Pathname:sbin>
#   #<Pathname:src>
#   #<Pathname:man>

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

See #children

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 477

def each_child(with_directory=true, &b)
  children(with_directory).each(&b)
end

#each_entry

Iterates over the entries (files and subdirectories) in the directory, yielding a Pathname object for each entry.

#each_filename

Iterates over each component of the path.

Pathname.new("/usr/bin/ruby").each_filename {|filename| ... }
  # yields "usr", "bin", and "ruby".

Returns an Enumerator if no block was given.

enum = Pathname.new("/usr/bin/ruby").each_filename
  # ... do stuff ...
enum.each { |e| ... }
  # yields "usr", "bin", and "ruby".
[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 263

def each_filename # :yield: filename
  return to_enum(__method__) unless block_given?
  _, names = split_names(@path)
  names.each {|filename| yield filename }
  nil
end

#each_line {|line| ... } #each_line(sep=$/ [, open_args]) {|line| ... } ⇒ nil #each_line(limit [, open_args]) {|line| ... } ⇒ nil #each_line(sep, limit [, open_args]) {|line| ... } ⇒ nil #each_line(...) ⇒ Enumerator

Iterates over each line in the file and yields a String object for each.

#entries

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

The results contains just the names in the directory, without any trailing slashes or recursive look-up.

pp Pathname.new('/usr/local').entries
#=> [#<Pathname:share>,
#    #<Pathname:lib>,
#    #<Pathname:..>,
#    #<Pathname:include>,
#    #<Pathname:etc>,
#    #<Pathname:bin>,
#    #<Pathname:man>,
#    #<Pathname:games>,
#    #<Pathname:.>,
#    #<Pathname:sbin>,
#    #<Pathname:src>]

The result may contain the current directory #<Pathname:.> and the parent directory #<Pathname:..>.

If you don't want . and .. and want directories, consider #children.

#eql?(other)

Alias for #==.

#expand_path(*args)

Returns the absolute path for the file.

See File.expand_path.

#extname

Returns the file's extension.

See File.extname.

#find(ignore_error: true)

Iterates over the directory tree in a depth first manner, yielding a Pathname for each file under “this” directory.

Returns an Enumerator if no block is given.

Since it is implemented by the standard library module Find, Find.prune can be used to control the traversal.

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

See Find.find

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 545

def find(ignore_error: true) # :yield: pathname
  return to_enum(__method__, ignore_error: ignore_error) unless block_given?
  require 'find'
  if @path == '.'
    Find.find(@path, ignore_error: ignore_error) {|f| yield self.class.new(f.sub(%r{\A\./}, '')) }
  else
    Find.find(@path, ignore_error: ignore_error) {|f| yield self.class.new(f) }
  end
end

#fnmatch(pattern, [flags]) ⇒ String #fnmatch?(pattern, [flags]) ⇒ String
Also known as: #fnmatch?

Return true if the receiver matches the given pattern.

See File.fnmatch.

#fnmatch(pattern, [flags]) ⇒ String #fnmatch?(pattern, [flags]) ⇒ String

Alias for #fnmatch.

#freezeObject

Freezes this Pathname.

See Object.freeze.

#ftypeString

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

See File.ftype.

#join(*args)

Joins the given pathnames onto self to create a new Pathname object.

path0 = Pathname.new("/usr")                # Pathname:/usr
path0 = path0.join("bin/ruby")              # Pathname:/usr/bin/ruby
    # is the same as
path1 = Pathname.new("/usr") + "bin/ruby"   # Pathname:/usr/bin/ruby
path0 == path1
    #=> true
[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 394

def join(*args)
  return self if args.empty?
  result = args.pop
  result = Pathname.new(result) unless Pathname === result
  return result if result.absolute?
  args.reverse_each {|arg|
    arg = Pathname.new(arg) unless Pathname === arg
    result = arg + result
    return result if result.absolute?
  }
  self + result
end

#lchmodInteger

Same as #chmod, but does not follow symbolic links.

See File.lchmod.

#lchownInteger

Same as #chown, but does not follow symbolic links.

See File.lchown.

#lstat

See File.lstat.

#mkdir(*args)

Create the referenced directory.

See Dir.mkdir.

#mkpath

Creates a full path, including any intermediate directories that don't yet exist.

See FileUtils.mkpath and FileUtils.mkdir_p

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 562

def mkpath
  require 'fileutils'
  FileUtils.mkpath(@path)
  nil
end

#mtimeTime

Returns the last modified time of the file.

See File.mtime.

#open(*args)

Opens the file for reading or writing.

See File.open.

#opendir

Opens the referenced directory.

See Dir.open.

#parent

Returns the parent directory.

This is same as self + '..'.

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 189

def parent
  self + '..'
end

#read([length [, offset]]) ⇒ String #read([length [, offset]], open_args) ⇒ String

Returns all data from the file, or the first N bytes if specified.

See IO.read.

#readlines(sep=$/ [, open_args]) ⇒ Array #readlines(limit [, open_args]) ⇒ Array #readlines(sep, limit [, open_args]) ⇒ Array

Returns all the lines from the file.

See IO.readlines.

#realdirpath(*args)

Returns the real (absolute) pathname of self in the actual filesystem.

Does not contain symlinks or useless dots, .. and ..

The last component of the real pathname can be nonexistent.

#realpath(*args)

Returns the real (absolute) pathname for self in the actual filesystem.

Does not contain symlinks or useless dots, .. and ..

All components of the pathname must exist when this method is called.

#relative_path_from(base_directory)

Returns a relative path from the given base_directory to the receiver.

If self is absolute, then base_directory must be absolute too.

If self is relative, then base_directory must be relative too.

This method doesn't access the filesystem. It assumes no symlinks.

ArgumentError is raised when it cannot find a relative path.

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 492

def relative_path_from(base_directory)
  dest_directory = self.cleanpath.to_s
  base_directory = base_directory.cleanpath.to_s
  dest_prefix = dest_directory
  dest_names = []
  while r = chop_basename(dest_prefix)
    dest_prefix, basename = r
    dest_names.unshift basename if basename != '.'
  end
  base_prefix = base_directory
  base_names = []
  while r = chop_basename(base_prefix)
    base_prefix, basename = r
    base_names.unshift basename if basename != '.'
  end
  unless SAME_PATHS[dest_prefix, base_prefix]
    raise ArgumentError, "different prefix: #{dest_prefix.inspect} and #{base_directory.inspect}"
  end
  while !dest_names.empty? &&
        !base_names.empty? &&
        SAME_PATHS[dest_names.first, base_names.first]
    dest_names.shift
    base_names.shift
  end
  if base_names.include? '..'
    raise ArgumentError, "base_directory has ..: #{base_directory.inspect}"
  end
  base_names.fill('..')
  relpath_names = base_names + dest_names
  if relpath_names.empty?
    Pathname.new('.')
  else
    Pathname.new(File.join(*relpath_names))
  end
end

#rename(to)

Rename the file.

See File.rename.

#rmdir

Remove the referenced directory.

See Dir.rmdir.

#rmtree

Recursively deletes a directory, including all directories beneath it.

See FileUtils.rm_r

[ GitHub ]

  
# File 'ext/pathname/lib/pathname.rb', line 571

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

#split

Returns the #dirname and the #basename in an Array.

See File.split.

#stat

Returns a File::Stat object.

See File.stat.

#sub(*args)

Return a pathname which is substituted by String#sub.

path1 = Pathname.new('/usr/bin/perl')
path1.sub('perl', 'ruby')
    #=> #<Pathname:/usr/bin/ruby>

#sub_ext(repl)

Return a pathname with repl added as a suffix to the basename.

If self has no extension part, repl is appended.

Pathname.new('/usr/bin/shutdown').sub_ext('.rb')
    #=> #<Pathname:/usr/bin/shutdown.rb>

#sysopen([mode, [perm]]) ⇒ Fixnum

See IO.sysopen.

#taintObject

Taints this Pathname.

See Object.taint.

#to_sString #to_pathString

Alias for #to_s.

#to_sString #to_pathString
Also known as: #to_path

Return the path as a String.

to_path is implemented so Pathname objects are usable with File.open, etc.

#truncate(length)

Truncates the file to length bytes.

See File.truncate.

#untaintObject

Untaints this Pathname.

See Object.untaint.

#utime(atime, mtime)

Update the access and modification times of the file.

See File.utime.

#write(string, [offset]) ⇒ Fixnum #write(string, [offset], open_args) ⇒ Fixnum

Writes contents to the file.

See IO.write.