Class
pathname.rb
Object-Oriented Pathname Class
- Author
-
Tanaka Akira <akr@m17n.org>
- Documentation
-
Author and Gavin Sinclair
For documentation, see class Pathname.
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 isdir = pn.directory? dir = pn.dirname base = pn.basename dir, base = pn.split data = pn.read pn.open { |f| _ } pn.each_line { |line| _ }
Example 2: Using standard Ruby
pn = "/usr/bin/ruby" size = File.size(pn) isdir = File.directory?(pn) dir = File.dirname(pn) base = File.basename(pn) dir, base = File.split(pn) data = File.read(pn) File.open(pn) { |f| _ } File.foreach(pn) { |line| _ }
Example 3: Special features
p1 = Pathname.new("/usr/lib") p2 = p1 + "ruby/1.8" p3 = p1.parent p4 = p2.relative_path_from(p3) pwd = Pathname.pwd pwd.absolute? p5 = Pathname.new "." p5 = p5 + "music/../articles" p5.cleanpath p5.realpath p5.children
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:
-
each_entry(&block)
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.
Constants
Regexp that matches an absolute path.
Separator list string.
Regexp that matches a separator.
The version string.
Class Methods
Creates a tmp directory and wraps the returned path in a Pathname object.
Note that you need to require ‘pathname’ to use this method.
See Dir.mktmpdir
Create a Pathname object from the given String (or String-like object). If path contains a NUL character (\0), an ArgumentError is raised.
Instance Methods
Provides a case-sensitive comparison operator for pathnames.
Pathname.new('/usr') <=> Pathname.new('/usr/bin') Pathname.new('/usr/bin') <=> Pathname.new('/usr/bin') Pathname.new('/usr/bin') <=> Pathname.new('/USR/BIN')
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.
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.
Appends a pathname fragment to self to produce a new Pathname object. Since other is considered as a path relative to self, if other is an absolute path, the new Pathname object is created from just other.
p1 = Pathname.new("/usr") p2 = p1 + "bin/ruby" p3 = p1 + "/etc/passwd" p4 = p1 / "bin/ruby" p5 = p1 / "/etc/passwd"
This method doesn’t access the file system; it is pure string manipulation.
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? p = Pathname.new('not/so/sure') p.absolute?
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.new('path/to/some/file.rb').ascend {|v| p v}
Returns an Enumerator if no block was given.
enum = Pathname.new("/usr/bin/ruby").ascend
# ... do stuff ...
enum.each { |e| ... }
# yields Pathnames /usr/bin/ruby, /usr/bin, /usr, and /.
It doesn’t access the filesystem.
See File.binread. Returns all the bytes from the file, or the first N if specified.
Writes contents to the file, opening it in binary mode.
See File.binwrite.
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.
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 Pathname#realpath.
See File.ctime. Returns last (directory entry, not file) change time.
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.new('path/to/some/file.rb').descend {|v| p v}
Returns an Enumerator if no block was given.
enum = Pathname.new("/usr/bin/ruby").descend
# ... do stuff ...
enum.each { |e| ... }
# yields Pathnames /, /usr, /usr/bin, and /usr/bin/ruby.
It doesn’t access the filesystem.
See File.dirname. Returns all but the last component of the path.
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").each_child(false) {|f| p f }
Note that the results never contain the entries . and .. in the directory because they are not children.
Iterates over the entries (files and subdirectories) in the directory. It yields a Pathname object for each entry.
This method has existed since 1.8.1.
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".
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.
Return the entries (files and subdirectories) in the directory, each as a Pathname object.
Iterates over the directory tree in a depth first manner, yielding a Pathname for each file under “this” directory.
Note that you need to require ‘pathname’ to use this method.
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
See File.fnmatch. Return true if the receiver matches the given pattern.
Freze self.
See File.ftype. Returns “type” of file (“file”, “directory”, etc).
Returns or yields Pathname objects.
Pathname("ruby-2.4.2").glob("R*.md")
See Dir.glob. This method uses the base keyword argument of Dir.glob.
Joins the given pathnames onto self to create a new Pathname object. This is effectively the same as using Pathname#+ to append self and all arguments sequentially.
path0 = Pathname.new("/usr") path0 = path0.join("bin/ruby") path1 = Pathname.new("/usr") + "bin/ruby" path0 == path1
Update the access and modification times of the file.
Same as Pathname#utime, but does not follow symbolic links.
See File.lutime.
See Dir.mkdir. Create the referenced directory.
Returns true if self points to a mountpoint.
See File.open. Opens the file for reading or writing.
Returns the parent directory.
This is same as self + '..'.
See File.read. Returns all data from the file, or the first N bytes if specified.
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.
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.
The opposite of Pathname#absolute?
It returns false if the pathname begins with a slash.
p = Pathname.new('/im/sure') p.relative? p = Pathname.new('not/so/sure') p.relative?
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.
Note that this method does not handle situations where the case sensitivity of the filesystem in use differs from the operating system default.
See Dir.rmdir. Remove the referenced directory.
Recursively deletes a directory, including all directories beneath it.
Note that you need to require ‘pathname’ to use this method.
See FileUtils.rm_rf
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/...
Return a pathname which is substituted by String#sub.
path1 = Pathname.new('/usr/bin/perl') path1.sub('perl', 'ruby')
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')
See File.utime. Update the access and modification times.