| Class | Pathname |
| In: |
pathname.rb
|
| Parent: | Object |
Pathname
Pathname represents a pathname which locates a file in a filesystem. It supports only Unix style pathnames. It does not represent the file itself. 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 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 Pathname
require 'pathname'
p = Pathname.new("/usr/bin/ruby")
size = p.size # 27662
isdir = p.directory? # false
dir = p.dirname # Pathname:/usr/bin
base = p.basename # Pathname:ruby
dir, base = p.split # [Pathname:/usr/bin, Pathname: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 = 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. Except for mountpoint?, children, and realpath, they don’t access the filesystem.
- +
- join
- parent
- root?
- absolute?
- relative?
- relative_path_from
- each_filename
- cleanpath
- realpath
- children
- mountpoint?
File status predicate methods
These methods are a facade for FileTest:
- blockdev?
- chardev?
- directory?
- executable?
- executable_real?
- exist?
- file?
- grpowned?
- owned?
- pipe?
- readable?
- readable_real?
- setgid?
- setuid?
- size
- size?
- socket?
- sticky?
- symlink?
- writable?
- writable_real?
- zero?
File property and manipulation methods
These methods are a facade for File:
- atime
- ctime
- mtime
- chmod(mode)
- lchmod(mode)
- chown(owner, group)
- lchown(owner, group)
- fnmatch(pattern, *args)
- fnmatch?(pattern, *args)
- ftype
- make_link(old)
- open(*args, &block)
- readlink
- rename(to)
- stat
- lstat
- make_symlink(old)
- truncate(length)
- utime(atime, mtime)
- basename(*args)
- dirname
- extname
- expand_path(*args)
- split
Directory methods
These methods are a facade for Dir:
- Pathname.glob(*args)
- Pathname.getwd / Pathname.pwd
- rmdir
- entries
- each_entry(&block)
- mkdir(*args)
- opendir(*args)
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 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.
Methods
External Aliases
| getwd | -> | pwd |
Public Class methods
Create a Pathname object from the given String (or String-like object). If path contains a NUL character (\0), an ArgumentError is raised.
# File pathname.rb, line 187
187: def initialize(path)
188: path = path.to_str if path.respond_to? :to_str
189: @path = path.dup
190:
191: if /\0/ =~ @path
192: raise ArgumentError, "pathname contains \\0: #{@path.inspect}"
193: end
194:
195: self.taint if @path.tainted?
196: end
Public Instance methods
Pathname#+ appends a pathname fragment to this one 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
This method doesn’t access the file system; it is pure string manipulation.
# File pathname.rb, line 433
433: def +(other)
434: other = Pathname.new(other) unless Pathname === other
435:
436: return other if other.absolute?
437:
438: path1 = @path
439: path2 = other.to_s
440: while m2 = %r{\A\.\.(?:/+|\z)}.match(path2) and
441: m1 = %r{(\A|/+)([^/]+)\z}.match(path1) and
442: %r{\A(?:\.|\.\.)\z} !~ m1[2]
443: path1 = m1[1].empty? ? '.' : '/' if (path1 = m1.pre_match).empty?
444: path2 = '.' if (path2 = m2.post_match).empty?
445: end
446: if %r{\A/+\z} =~ path1
447: while m2 = %r{\A\.\.(?:/+|\z)}.match(path2)
448: path2 = '.' if (path2 = m2.post_match).empty?
449: end
450: end
451:
452: return Pathname.new(path2) if path1 == '.'
453: return Pathname.new(path1) if path2 == '.'
454:
455: if %r{/\z} =~ path1
456: Pathname.new(path1 + path2)
457: else
458: Pathname.new(path1 + '/' + path2)
459: end
460: end
Provides for comparing pathnames, case-sensitively.
# File pathname.rb, line 215
215: def <=>(other)
216: return nil unless Pathname === other
217: @path.tr('/', "\0") <=> other.to_s.tr('/', "\0")
218: end
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 pathname.rb, line 207
207: def ==(other)
208: return false unless Pathname === other
209: other.to_s == @path
210: end
Predicate method for testing whether a path is absolute. It returns true if the pathname begins with a slash.
# File pathname.rb, line 404
404: def absolute?
405: %r{\A/} =~ @path ? true : false
406: end
See File.atime. Returns last access time.
# File pathname.rb, line 598
598: def atime() File.atime(@path) end
See File.basename. Returns the last component of the path.
# File pathname.rb, line 659
659: def basename(*args) Pathname.new(File.basename(@path, *args)) end
See FileTest.blockdev?.
# File pathname.rb, line 693
693: def blockdev?() FileTest.blockdev?(@path) end
See FileTest.chardev?.
# File pathname.rb, line 696
696: def chardev?() FileTest.chardev?(@path) end
Pathname#chdir is obsoleted at 1.8.1.
# File pathname.rb, line 775
775: def chdir(&block)
776: warn "Pathname#chdir is obsoleted. Use Dir.chdir."
777: Dir.chdir(@path, &block)
778: end
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:
p = Pathname("/usr/lib/ruby/1.8")
p.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, ... ]
p.children(false)
# -> [ Pathname:English.rb, Pathname:Env.rb, Pathname: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 pathname.rb, line 502
502: def children(with_directory=true)
503: with_directory = false if @path == '.'
504: result = []
505: Dir.foreach(@path) {|e|
506: next if e == '.' || e == '..'
507: if with_directory
508: result << Pathname.new(File.join(@path, e))
509: else
510: result << Pathname.new(e)
511: end
512: }
513: result
514: end
See File.chmod. Changes permissions.
# File pathname.rb, line 607
607: def chmod(mode) File.chmod(mode, @path) end
See File.chown. Change owner and group of file.
# File pathname.rb, line 613
613: def chown(owner, group) File.chown(owner, group, @path) end
Pathname#chroot is obsoleted at 1.8.1.
# File pathname.rb, line 781
781: def chroot
782: warn "Pathname#chroot is obsoleted. Use Dir.chroot."
783: Dir.chroot(@path)
784: end
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 pathname.rb, line 245
245: def cleanpath(consider_symlink=false)
246: if consider_symlink
247: cleanpath_conservative
248: else
249: cleanpath_aggressive
250: end
251: end
See File.ctime. Returns last (directory entry, not file) change time.
# File pathname.rb, line 601
601: def ctime() File.ctime(@path) end
Pathname#dir_foreach is obsoleted at 1.8.1.
# File pathname.rb, line 799
799: def dir_foreach(*args, &block)
800: warn "Pathname#dir_foreach is obsoleted. Use Pathname#each_entry."
801: each_entry(*args, &block)
802: end
See FileTest.directory?.
# File pathname.rb, line 711
711: def directory?() FileTest.directory?(@path) end
See File.dirname. Returns all but the last component of the path.
# File pathname.rb, line 662
662: def dirname() Pathname.new(File.dirname(@path)) end
Iterates over each component of the path.
Pathname.new("/usr/bin/ruby").each_filename {|filename| ... }
# yields "usr", "bin", and "ruby".
# File pathname.rb, line 419
419: def each_filename # :yield: s
420: @path.scan(%r{[^/]+}) { yield $& }
421: end
See FileTest.executable?.
# File pathname.rb, line 699
699: def executable?() FileTest.executable?(@path) end
See FileTest.executable_real?.
# File pathname.rb, line 702
702: def executable_real?() FileTest.executable_real?(@path) end
See File.expand_path.
# File pathname.rb, line 668
668: def expand_path(*args) Pathname.new(File.expand_path(@path, *args)) end
See File.extname. Returns the file’s extension.
# File pathname.rb, line 665
665: def extname() File.extname(@path) end
Pathname#find is an iterator to traverse a directory tree in a depth first manner. It yields a Pathname 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 pathname.rb, line 828
828: def find(&block) # :yield: p
829: require 'find'
830: if @path == '.'
831: Find.find(@path) {|f| yield Pathname.new(f.sub(%r{\A\./}, '')) }
832: else
833: Find.find(@path) {|f| yield Pathname.new(f) }
834: end
835: end
See File.fnmatch. Return true if the receiver matches the given pattern.
# File pathname.rb, line 620
620: def fnmatch(pattern, *args) File.fnmatch(pattern, @path, *args) end
This method is obsoleted at 1.8.1. Use each_line or each_entry.
# File pathname.rb, line 872
872: def foreach(*args, &block)
873: warn "Pathname#foreach is obsoleted. Use each_line or each_entry."
874: if FileTest.directory? @path
875: # For polymorphism between Dir.foreach and IO.foreach,
876: # Pathname#foreach doesn't yield Pathname object.
877: Dir.foreach(@path, *args, &block)
878: else
879: IO.foreach(@path, *args, &block)
880: end
881: end
Pathname#foreachline is obsoleted at 1.8.1. Use each_line.
# File pathname.rb, line 578
578: def foreachline(*args, &block)
579: warn "Pathname#foreachline is obsoleted. Use Pathname#each_line."
580: each_line(*args, &block)
581: end
See File.ftype. Returns "type" of file ("file", "directory", etc).
# File pathname.rb, line 627
627: def ftype() File.ftype(@path) end
See FileTest.grpowned?.
# File pathname.rb, line 708
708: def grpowned?() FileTest.grpowned?(@path) end
Pathname#join joins pathnames.
path0.join(path1, …, pathN) is the same as path0 + path1 + … + pathN.
# File pathname.rb, line 468
468: def join(*args)
469: args.unshift self
470: result = args.pop
471: result = Pathname.new(result) unless Pathname === result
472: return result if result.absolute?
473: args.reverse_each {|arg|
474: arg = Pathname.new(arg) unless Pathname === arg
475: result = arg + result
476: return result if result.absolute?
477: }
478: result
479: end
See File.lchown.
# File pathname.rb, line 616
616: def lchown(owner, group) File.lchown(owner, group, @path) end
Pathname#link is confusing and obsoleted because the receiver/argument order is inverted to corresponding system call.
# File pathname.rb, line 676
676: def link(old)
677: warn 'Pathname#link is obsoleted. Use Pathname#make_link.'
678: File.link(old, @path)
679: end
See File.link. Creates a hard link.
# File pathname.rb, line 630
630: def make_link(old) File.link(old, @path) end
See File.symlink. Creates a symbolic link.
# File pathname.rb, line 650
650: def make_symlink(old) File.symlink(old, @path) end
See Dir.mkdir. Create the referenced directory.
# File pathname.rb, line 805
805: def mkdir(*args) Dir.mkdir(@path, *args) end
See FileUtils.mkpath. Creates a full path, including any intermediate directories that don’t yet exist.
# File pathname.rb, line 842
842: def mkpath
843: require 'fileutils'
844: FileUtils.mkpath(@path)
845: nil
846: end
mountpoint? returns true if self points to a mountpoint.
# File pathname.rb, line 380
380: def mountpoint?
381: begin
382: stat1 = self.lstat
383: stat2 = self.parent.lstat
384: stat1.dev == stat2.dev && stat1.ino == stat2.ino ||
385: stat1.dev != stat2.dev
386: rescue Errno::ENOENT
387: false
388: end
389: end
See File.mtime. Returns last modification time.
# File pathname.rb, line 604
604: def mtime() File.mtime(@path) end
See File.open. Opens the file for reading or writing.
# File pathname.rb, line 633
633: def open(*args, &block) # :yield: file
634: File.open(@path, *args, &block)
635: end
See Dir.open.
# File pathname.rb, line 811
811: def opendir(&block) # :yield: dir
812: Dir.open(@path, &block)
813: end
See IO.read. Returns all the bytes from the file, or the first N if specified.
# File pathname.rb, line 585
585: def read(*args) IO.read(@path, *args) end
See FileTest.readable?.
# File pathname.rb, line 726
726: def readable?() FileTest.readable?(@path) end
See FileTest.readable_real?.
# File pathname.rb, line 729
729: def readable_real?() FileTest.readable_real?(@path) end
See IO.readlines. Returns all the lines from the file.
# File pathname.rb, line 588
588: def readlines(*args) IO.readlines(@path, *args) end
See File.readlink. Read symbolic link.
# File pathname.rb, line 638
638: def readlink() Pathname.new(File.readlink(@path)) end
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 pathname.rb, line 311
311: def realpath(*args)
312: unless args.empty?
313: warn "The argument for Pathname#realpath is obsoleted."
314: end
315: force_absolute = args.fetch(0, true)
316:
317: if %r{\A/} =~ @path
318: top = '/'
319: unresolved = @path.scan(%r{[^/]+})
320: elsif force_absolute
321: # Although POSIX getcwd returns a pathname which contains no symlink,
322: # 4.4BSD-Lite2 derived getcwd may return the environment variable $PWD
323: # which may contain a symlink.
324: # So the return value of Dir.pwd should be examined.
325: top = '/'
326: unresolved = Dir.pwd.scan(%r{[^/]+}) + @path.scan(%r{[^/]+})
327: else
328: top = ''
329: unresolved = @path.scan(%r{[^/]+})
330: end
331: resolved = []
332:
333: until unresolved.empty?
334: case unresolved.last
335: when '.'
336: unresolved.pop
337: when '..'
338: resolved.unshift unresolved.pop
339: else
340: loop_check = {}
341: while (stat = File.lstat(path = top + unresolved.join('/'))).symlink?
342: symlink_id = "#{stat.dev}:#{stat.ino}"
343: raise Errno::ELOOP.new(path) if loop_check[symlink_id]
344: loop_check[symlink_id] = true
345: if %r{\A/} =~ (link = File.readlink(path))
346: top = '/'
347: unresolved = link.scan(%r{[^/]+})
348: else
349: unresolved[-1,1] = link.scan(%r{[^/]+})
350: end
351: end
352: next if (filename = unresolved.pop) == '.'
353: if filename != '..' && resolved.first == '..'
354: resolved.shift
355: else
356: resolved.unshift filename
357: end
358: end
359: end
360:
361: if top == '/'
362: resolved.shift while resolved[0] == '..'
363: end
364:
365: if resolved.empty?
366: Pathname.new(top.empty? ? '.' : '/')
367: else
368: Pathname.new(top + resolved.join('/'))
369: end
370: end
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 pathname.rb, line 527
527: def relative_path_from(base_directory)
528: if self.absolute? != base_directory.absolute?
529: raise ArgumentError,
530: "relative path between absolute and relative path: #{self.inspect}, #{base_directory.inspect}"
531: end
532:
533: dest = []
534: self.cleanpath.each_filename {|f|
535: next if f == '.'
536: dest << f
537: }
538:
539: base = []
540: base_directory.cleanpath.each_filename {|f|
541: next if f == '.'
542: base << f
543: }
544:
545: while !base.empty? && !dest.empty? && base[0] == dest[0]
546: base.shift
547: dest.shift
548: end
549:
550: if base.include? '..'
551: raise ArgumentError, "base_directory has ..: #{base_directory.inspect}"
552: end
553:
554: base.fill '..'
555: relpath = base + dest
556: if relpath.empty?
557: Pathname.new(".")
558: else
559: Pathname.new(relpath.join('/'))
560: end
561: end
See File.rename. Rename the file.
# File pathname.rb, line 641
641: def rename(to) File.rename(@path, to) end
See Dir.rmdir. Remove the referenced directory.
# File pathname.rb, line 808
808: def rmdir() Dir.rmdir(@path) end
See FileUtils.rm_r. Deletes a directory and all beneath it.
# File pathname.rb, line 849
849: def rmtree
850: # The name "rmtree" is borrowed from File::Path of Perl.
851: # File::Path provides "mkpath" and "rmtree".
852: require 'fileutils'
853: FileUtils.rm_r(@path)
854: nil
855: end
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 pathname.rb, line 398
398: def root?
399: %r{\A/+\z} =~ @path ? true : false
400: end