Class: Path
- Inherits:
-
Object
- Object
- Path
- Defined in:
- lib/path/implementation.rb,
lib/path.rb,
lib/path/io.rb,
lib/path/dir.rb,
lib/path/file.rb,
lib/path/find.rb,
lib/path/load.rb,
lib/path/parts.rb,
lib/path/version.rb,
lib/path/identity.rb,
lib/path/fileutils.rb,
lib/path/predicates.rb,
lib/path/require_tree.rb,
lib/path/compatibility.rb,
lib/path/file_predicates.rb
Overview
All methods from FileTest and all predicates from File are included
Loading collapse
- LOADERS =
The list of loaders. See register_loader.
{}
Constant Summary collapse
- VERSION =
The version of the gem. Set here to avoid duplication and allow introspection.
'2.1.0'
- SAME_PATHS =
if File::FNM_SYSCASE.nonzero? lambda { |a,b| a.casecmp(b).zero? } else lambda { |a,b| a == b } end
Identity collapse
-
#path ⇒ Object
(also: #to_s, #to_path, #to_str)
readonly
Returns the
path
as a String.
IO collapse
-
#append(contents, *open_args) ⇒ Object
Appends
contents
toself
. -
#binread(*args) ⇒ Object
Returns all the bytes from the file, or the first
N
if specified. -
#binwrite(contents, *open_args) ⇒ Object
Writes
contents
toself
. -
#each_line(*args) {|line| ... } ⇒ Object
(also: #lines)
Iterates over the lines in the file.
-
#head(bytes) ⇒ Object
Returns the first
bytes
bytes of the file. -
#open(*args) {|file| ... } ⇒ Object
Opens the file for reading or writing.
-
#read(*args) ⇒ Object
Returns all data from the file, or the first
bytes
bytes if specified. -
#readlines(*args) ⇒ Object
Returns all the lines from the file.
-
#rewrite {|contents| ... } ⇒ Object
Rewrites contents of
self
. -
#sysopen(*args) ⇒ Object
See
IO.sysopen
. -
#tail(bytes) ⇒ Object
Returns the last
bytes
bytes of the file. -
#write(contents, *open_args) ⇒ Object
Writes
contents
toself
.
Directory collapse
-
.getwd ⇒ Object
(also: cwd, pwd)
Returns the current working directory as a Path.
-
.glob(pattern, flags = 0) {|path| ... } ⇒ Object
Returns or yields Path objects.
-
.glob_escape(path) ⇒ Object
Escape the path to be suitable for globbing (so it contains no globbing special characters).
-
#chdir(&block) ⇒ Object
Changes the current working directory of the process to self.
-
#children(with_directory = true) ⇒ Object
Returns the children of the directory (files and subdirectories, not recursive) as an array of Path objects.
-
#each_child(with_directory = true) {|child| ... } ⇒ Object
Iterates over the children of the directory (files and subdirectories, not recursive).
-
#each_entry {|entry| ... } ⇒ Object
deprecated
Deprecated.
Use #each_child instead. This method is deprecated since it is too low level and likely useless in Ruby. But it is there for the sake of compatibility with Dir.foreach and Pathname#each_entry.
-
#entries ⇒ Object
deprecated
Deprecated.
Use #children instead. This method is deprecated since it is too low level and likely useless in Ruby. But it is there for the sake of compatibility with Dir.entries (and Pathname#entries).
-
#glob(pattern, flags = 0) {|path| ... } ⇒ Object
Returns or yields Path objects.
-
#mkdir(*args) ⇒ Object
Create the referenced directory and returns self.
-
#opendir {|dir| ... } ⇒ Object
See
Dir.open
. -
#rmdir ⇒ Object
Remove the referenced directory.
-
#siblings(with_directory = true) ⇒ Object
Equivalent of parent.children - [self].
File collapse
-
#atime ⇒ Object
Returns the last access time.
-
#chmod(mode) ⇒ Object
Changes permissions of
path
. -
#chown(owner, group) ⇒ Object
Changes the owner and group of
path
. -
#ctime ⇒ Object
Returns the last change time (of the directory entry, not the file itself).
-
#expand(*args) ⇒ Object
(also: #expand_path)
Expands
path
, making it absolute. -
#ftype ⇒ Object
Returns “type” of file (“file”, “directory”, etc).
-
#lchmod(mode) ⇒ Object
Changes permissions of
path
, not following symlink. -
#lchown(owner, group) ⇒ Object
Changes the owner and group of
path
, not following symlink. -
#lstat ⇒ Object
Returns the stat of
path
as aFile::Stat
object, not following symlink. -
#make_link(target) ⇒ Object
Creates a hard link to
target
and returns self. -
#make_symlink(target) ⇒ Object
Creates a symbolic link to
target
and returns self. -
#mtime ⇒ Object
Returns last modification time.
-
#readlink ⇒ Object
Reads the symbolic link.
-
#realdirpath(basedir = nil) ⇒ Object
Returns the real (absolute) path of
self
in the actual filesystem. -
#realpath(basedir = nil) ⇒ Object
(also: #real)
Returns the real (absolute) path for
self
in the actual filesystem not containing symlinks or useless dots. -
#rename(to) ⇒ Object
Renames the file and returns the new Path.
-
#size ⇒ Object
Returns the file size in bytes.
-
#stat ⇒ Object
Returns the stat of
path
as aFile::Stat
object. -
#truncate(length) ⇒ Object
Truncates the file to
length
bytes. -
#unlink ⇒ Object
(also: #delete)
Removes a file using
File.unlink
. -
#utime(atime, mtime) ⇒ Object
Updates the access and modification times.
Loading collapse
-
.register_loader(*extensions) {|path| ... } ⇒ Object
Registers a new loader (a block which will be called with the Path to load) for the given extensions (either with the leading dot or not).
-
#load ⇒ Object
Path#load helps loading data from various files.
Path parts collapse
-
.dotted_ext(ext) ⇒ Object
add a leading .
-
.pure_ext(ext) ⇒ Object
remove the leading .
-
#add_extension(ext) ⇒ Object
(also: #add_ext)
Adds
ext
as an extension topath
. -
#ascend {|path| ... } ⇒ Object
(also: #ancestors)
Iterates over each element in the given path in ascending order.
-
#base(*args) ⇒ Object
(also: #basename)
Returns the last component of the path.
-
#descend {|path| ... } ⇒ Object
Iterates over each element in the given path in descending order.
-
#dir ⇒ Object
(also: #dirname)
Returns all but the last component of the path.
-
#each_filename {|filename| ... } ⇒ Object
Iterates over each component of the path.
-
#ext ⇒ Object
(also: #extname)
Returns the extension, with a leading dot.
-
#pure_ext ⇒ Object
#ext without leading dot.
-
#replace_extension(ext) ⇒ Object
(also: #sub_ext)
Replaces the last extension of
path
withext
. -
#split ⇒ Object
Returns the #dirname and the #basename in an Array.
-
#stem ⇒ Object
Returns the last component of the path, without the extension: base(ext).
-
#without_extension ⇒ Object
(also: #rm_ext)
Removes the last extension of
path
.
Identity collapse
-
._load(path) ⇒ Object
Marshal loading.
-
.json_create(json) ⇒ Object
JSON loading.
-
.like ⇒ Object
A matcher responding to #===.
-
.like?(object) ⇒ Boolean
Whether
object
looks like a path. -
.new(*args) ⇒ Object
(also: [])
Creates a new Path.
-
.to_proc ⇒ Object
A class constructor.
-
#<=>(other) ⇒ Object
Provides a case-sensitive comparison operator for paths.
-
#==(other) ⇒ Object
(also: #eql?)
Compare this path with
other
. -
#_dump(level) ⇒ Object
Marshal dumping.
-
#hash ⇒ Object
The hash value of the
path
. -
#init_with(coder) ⇒ Object
Psych loading.
-
#initialize(*parts) ⇒ Path
constructor
Creates a new Path.
-
#inspect ⇒ Object
A representation of the
path
. -
#to_json(*args) ⇒ Object
JSON dumping.
-
#to_sym ⇒ Object
Returns the
path
as a Symbol. -
#yaml_initialize(tag, ivars) ⇒ Object
YAML loading.
File utilities collapse
-
#chmod_r(mode) ⇒ Object
Recusively changes permissions.
-
#chown_r(owner, group) ⇒ Object
Recusively changes owner and group.
-
#cp(to) ⇒ Object
(also: #copy)
Copies the file to
to
. -
#cp_r(to) ⇒ Object
Copies the file or directory recursively to the directory
to
. -
#has_same_contents?(file) ⇒ Boolean
Whether the contents of
path
andfile
are identical. -
#install(file, **options) ⇒ Object
Install
file
intopath
(the “prefix”, which should be a directory). -
#mkpath ⇒ Object
(also: #mkdir_p)
Creates a full path, including any intermediate directories that don’t yet exist.
-
#mv(to) ⇒ Object
(also: #move)
Moves
self
to theto
directory. -
#rm ⇒ Object
Removes the file using
FileUtils.rm
. -
#rm_f ⇒ Object
(also: #safe_unlink)
Removes the file, ignoring errors, using
FileUtils.rm_f
. -
#rm_rf ⇒ Object
Removes the file or directory recursively, ignoring errors, using
FileUtils.rm_f
. -
#rmtree ⇒ Object
(also: #rm_r)
Deletes a directory and all beneath it.
-
#touch ⇒ Object
Updates access and modification time or create an empty file.
- #touch! ⇒ Object
-
#uptodate?(*others) ⇒ Boolean
Returns whether
self
is newer than allothers
.
Path predicates collapse
-
#absolute? ⇒ Boolean
Whether a path is absolute.
-
#hidden? ⇒ Boolean
Whether this is a hidden path, i.e.
-
#mountpoint? ⇒ Boolean
Returns
true
ifself
points to a mountpoint. -
#relative? ⇒ Boolean
Whether a path is relative.
-
#root? ⇒ Boolean
Predicate for root directories.
Requiring collapse
-
.require_tree(directory = nil, options = {}) ⇒ Object
Requires all .rb files recursively under
directory
(or the current file’s directory if not given).
File predicates collapse
-
#blockdev? ⇒ Boolean
See
File.blockdev?
. -
#chardev? ⇒ Boolean
See
File.chardev?
. -
#directory? ⇒ Boolean
(also: #dir?)
See
File.directory?
. -
#executable? ⇒ Boolean
See
File.executable?
. -
#executable_real? ⇒ Boolean
See
File.executable_real?
. -
#exist? ⇒ Boolean
(also: #exists?)
See
File.exist?
. -
#file? ⇒ Boolean
See
File.file?
. -
#fnmatch?(pattern, *args) ⇒ Boolean
Return
true
if the receiver matches the given pattern. -
#grpowned? ⇒ Boolean
See
File.grpowned?
. -
#identical?(path) ⇒ Boolean
See
File.identical?
. -
#owned? ⇒ Boolean
See
File.owned?
. -
#pipe? ⇒ Boolean
See
File.pipe?
. -
#readable? ⇒ Boolean
See
File.readable?
. -
#readable_real? ⇒ Boolean
See
File.readable_real?
. -
#setgid? ⇒ Boolean
See
File.setgid?
. -
#setuid? ⇒ Boolean
See
File.setuid?
. -
#size? ⇒ Boolean
See
File.size?
. -
#socket? ⇒ Boolean
See
File.socket?
. -
#sticky? ⇒ Boolean
See
File.sticky?
. -
#symlink? ⇒ Boolean
See
File.symlink?
. -
#world_readable? ⇒ Boolean
See
File.world_readable?
. -
#world_writable? ⇒ Boolean
See
File.world_writable?
. -
#writable? ⇒ Boolean
See
File.writable?
. -
#writable_real? ⇒ Boolean
See
File.writable_real?
. -
#zero? ⇒ Boolean
(also: #empty?)
See
File.zero?
.
Class Method Summary collapse
-
.backfind(path) ⇒ Object
Same as Path.file.backfind(path).
-
.configure(config) ⇒ Object
Configures the behavior of #+.
-
.dir(from = nil) ⇒ Object
Path to the directory of this file: Path(__FILE__).dir.
-
.file(from = nil) ⇒ Object
Path to the current file Path(__FILE__).
-
.null ⇒ Object
A Path to the null device on the current platform.
-
.relative(path, from = nil) ⇒ Object
Path relative to the directory of this file.
- .tmpchdir(prefix_suffix = nil, *rest) {|tmpdir| ... } ⇒ Object
- .tmpdir(prefix_suffix = nil, *rest) {|tmpdir| ... } ⇒ Object
- .tmpfile(basename = '', tmpdir = nil, options = nil) {|tmpfile| ... } ⇒ Object (also: tempfile)
-
.~(user = '') ⇒ Object
(also: home)
A Path to the home directory of
user
(defaults to the current user).
Instance Method Summary collapse
-
#+(other) ⇒ Object
The behavior depends on the configuration with Path.configure.
-
#/(other) ⇒ Object
Path#/ appends a path fragment to
self
to produce a new Path. -
#backfind(path) ⇒ Object
Ascends the parents until it finds the given
path
. -
#clean(consider_symlink = false) ⇒ Object
(also: #cleanpath)
Returns a cleaned version of
self
with consecutive slashes and useless dots removed. -
#find {|path| ... } ⇒ Object
Iterates over the directory tree in a depth first manner, yielding a Path for each file under “this” directory.
-
#inside?(ancestor) ⇒ Boolean
Whether
self
is insideancestor
, such thatancestor
is an ancestor ofself
. -
#join(*paths) ⇒ Object
Joins paths.
-
#outside?(ancestor) ⇒ Boolean
The opposite of #inside?.
-
#parent ⇒ Object
Returns the parent directory.
-
#relative_path_from(base_directory) ⇒ Object
(also: #relative_to, #%)
#relative_path_from returns a relative path from the given
base_directory
to the receiver. -
#relocate(from, to, new_ext = ext, &updater) ⇒ Object
Relocates this path somewhere else.
Constructor Details
#initialize(*parts) ⇒ Path
Creates a new Path. If multiple arguments are given, they are joined with File.join. The path will have File::ALT_SEPARATOR replaced with ‘/’ and if it begins with a ‘~’, it will be expanded (using File.expand_path). Accepts an Array of Strings, a Tempfile, anything that respond to #path, #to_path or #to_str with a String and defaults to calling #to_s.
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/path/identity.rb', line 57 def initialize(*parts) path = parts.size > 1 ? File.join(*parts) : parts.first @path = case path when Tempfile @_tmpfile = path # We would not want it to be GC'd path.path.dup when String path.dup else if path.respond_to? :to_path and String === path.to_path path.to_path.dup elsif path.respond_to? :path and String === path.path path.path.dup elsif path.respond_to? :to_str and String === path.to_str path.to_str.dup else path.to_s.dup end end init end |
Instance Attribute Details
#path ⇒ Object (readonly) Also known as: to_s, to_path, to_str
Returns the path
as a String. #path is implemented for better readability (file.path
instead of file.to_s
) and as an accessor. #to_path is implemented so Path objects are usable with open
, etc. #to_str is implemented so Path objects are usable with open
, etc with Ruby 1.8 (it is not defined in Ruby 1.9).
84 85 86 |
# File 'lib/path/identity.rb', line 84 def path @path end |
Class Method Details
._load(path) ⇒ Object
Marshal loading.
149 150 151 |
# File 'lib/path/identity.rb', line 149 def self._load path self.new(path) end |
.backfind(path) ⇒ Object
Same as Path.file.backfind(path). See #backfind.
48 49 50 |
# File 'lib/path.rb', line 48 def backfind(path) file(caller).backfind(path) end |
.configure(config) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/path/implementation.rb', line 48 def Path.configure(config) config = config[:+] unless [:defined, :warning, :error, :string].include? config raise ArgumentError, "Invalid configuration: #{config.inspect}" end if @plus_configured raise "Path.configure(:+ => ...) has already been called: #{@plus_configured}" end remove_method :+ if method_defined? :+ case config when :defined alias :+ :/ when :warning def +(other) warn 'Warning: use of deprecated Path#+ as Path#/: ' << "#{inspect} + #{other.inspect}\n#{caller.first}" self / other end when :error # nothing to do, the method has been removed when :string def +(other) warn 'Warning: use of deprecated Path#+ as String#+: ' << "#{inspect} + #{other.inspect}\n#{caller.first}" if $VERBOSE Path.new(to_s + other.to_s) end end @plus_configured = caller.first end |
.dir(from = nil) ⇒ Object
Path to the directory of this file: Path(__FILE__).dir.
19 20 21 22 |
# File 'lib/path.rb', line 19 def dir(from = nil) from ||= caller # this can not be moved as a default argument, JRuby optimizes it file(from).dir end |
.dotted_ext(ext) ⇒ Object
add a leading . to ext
if missing. Returns ” if ext
is empty.
10 11 12 |
# File 'lib/path/parts.rb', line 10 def self.dotted_ext(ext) ext = ext.to_s and (ext.empty? or ext.start_with?('.')) ? ext : ".#{ext}" end |
.file(from = nil) ⇒ Object
Path to the current file Path(__FILE__).
12 13 14 15 16 |
# File 'lib/path.rb', line 12 def file(from = nil) from ||= caller # this can not be moved as a default argument, JRuby optimizes it # v This : is there to define a group without capturing new(from.first.rpartition(/:\d+(?:$|:in )/).first). end |
.getwd ⇒ Object Also known as: cwd, pwd
Returns the current working directory as a Path. See Dir.getwd
.
22 23 24 |
# File 'lib/path/dir.rb', line 22 def Path.getwd new Dir.getwd end |
.glob(pattern, flags = 0) {|path| ... } ⇒ Object
Returns or yields Path objects. See Dir.glob
.
13 14 15 16 17 18 19 |
# File 'lib/path/dir.rb', line 13 def glob(pattern, flags = 0) if block_given? Dir.glob(pattern, flags) { |f| yield new(f) } else Dir.glob(pattern, flags).map(&Path) end end |
.glob_escape(path) ⇒ Object
Escape the path to be suitable for globbing (so it contains no globbing special characters)
7 8 9 |
# File 'lib/path/dir.rb', line 7 def glob_escape(path) path.gsub(/\[|\]|\*|\?|\{|\}/, '\\\\' + '\0') end |
.json_create(json) ⇒ Object
JSON loading.
139 140 141 |
# File 'lib/path/identity.rb', line 139 def self.json_create json new json['data'] end |
.like ⇒ Object
36 37 38 39 40 41 42 43 44 |
# File 'lib/path/identity.rb', line 36 def like @like ||= begin matcher = Object.new def matcher.===(object) Path.like?(object) end matcher end end |
.like?(object) ⇒ Boolean
Whether object
looks like a path. The current test checks if the object responds to #to_path, #path or #to_str.
25 26 27 |
# File 'lib/path/identity.rb', line 25 def like? object [:to_path, :path, :to_str].any? { |meth| object.respond_to? meth } end |
.new(*args) ⇒ Object Also known as: []
Creates a new Path. See #initialize.
6 7 8 9 10 11 12 |
# File 'lib/path/identity.rb', line 6 def new(*args) if args.size == 1 and Path === args.first args.first else super(*args) end end |
.null ⇒ Object
A Path to the null device on the current platform.
38 39 40 41 42 43 44 45 |
# File 'lib/path.rb', line 38 def null new case RbConfig::CONFIG['host_os'] when /mswin|mingw/ then 'NUL' when /amiga/i then 'NIL:' when /openvms/i then 'NL:' else '/dev/null' end end |
.pure_ext(ext) ⇒ Object
remove the leading . of ext
if present.
5 6 7 |
# File 'lib/path/parts.rb', line 5 def self.pure_ext(ext) ext = ext.to_s and ext.start_with?('.') ? ext[1..-1] : ext end |
.register_loader(*extensions) {|path| ... } ⇒ Object
Registers a new loader (a block which will be called with the Path to load) for the given extensions (either with the leading dot or not)
Path.register_loader('.marshal') { |file| Marshal.load file.read }
13 14 15 16 17 |
# File 'lib/path/load.rb', line 13 def self.register_loader(*extensions, &loader) extensions.each { |ext| LOADERS[Path.dotted_ext(ext)] = loader } end |
.relative(path, from = nil) ⇒ Object
Path relative to the directory of this file.
25 26 27 28 |
# File 'lib/path.rb', line 25 def relative(path, from = nil) from ||= caller # this can not be moved as a default argument, JRuby optimizes it new(path). dir(from) end |
.require_tree(directory = nil, options = {}) ⇒ Object
Requires all .rb files recursively under directory
(or the current file’s directory if not given).
The order of requires is alphabetical, but files having the same basename as a directory are required before files in this directory.
# in bar.rb
Path.require_tree
# require in this order:
# foo.rb
# foo/ext.rb
# foo/sub.rb
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/path/require_tree.rb', line 22 def self.require_tree(directory = nil, = {}) directory, = nil, directory if Hash === directory source = Path.file(caller) directory = Path.relative(directory || source.dir, caller) except = [:except] || [] directory.glob('**/*.rb').reject { |path| except.any? { |prefix| (path % directory).path.start_with?(prefix) } }.sort! { |a,b| if b.inside?(a.rm_ext) -1 elsif a.inside?(b.rm_ext) +1 else a <=> b end }.each { |file| require file.path unless source == file } end |
.tmpchdir(prefix_suffix = nil, *rest) {|tmpdir| ... } ⇒ Object
82 83 84 85 86 87 88 |
# File 'lib/path.rb', line 82 def tmpchdir(prefix_suffix = nil, *rest) tmpdir do |dir| dir.chdir do yield dir end end end |
.tmpdir(prefix_suffix = nil, *rest) {|tmpdir| ... } ⇒ Object
68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/path.rb', line 68 def tmpdir(prefix_suffix = nil, *rest) require 'tmpdir' dir = new Dir.mktmpdir(prefix_suffix, *rest) if block_given? begin yield dir ensure FileUtils.remove_entry_secure(dir) rescue nil end end dir end |
.tmpfile(basename = '', tmpdir = nil, options = nil) {|tmpfile| ... } ⇒ Object Also known as: tempfile
53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/path.rb', line 53 def tmpfile(basename = '', tmpdir = nil, = nil) tempfile = Tempfile.new(basename, *[tmpdir, ].compact) file = new tempfile if block_given? begin yield file ensure tempfile.close! end end file end |
.to_proc ⇒ Object
A class constructor.
%w[foo bar].map(&Path) # == [Path('foo'), Path('bar')]
18 19 20 |
# File 'lib/path/identity.rb', line 18 def to_proc lambda { |path| new(path) } end |
.~(user = '') ⇒ Object Also known as: home
A Path to the home directory of user
(defaults to the current user). The form with an argument (user
) is not supported on Windows.
32 33 34 |
# File 'lib/path.rb', line 32 def ~(user = '') new("~#{user}") end |
Instance Method Details
#+(other) ⇒ Object
|
# File 'lib/path/implementation.rb', line 82
|
#/(other) ⇒ Object
36 37 38 |
# File 'lib/path/implementation.rb', line 36 def /(other) Path.new(plus(@path, other.to_s)) end |
#<=>(other) ⇒ Object
Provides a case-sensitive comparison operator for paths.
98 99 100 101 |
# File 'lib/path/identity.rb', line 98 def <=>(other) return nil unless Path === other @path.tr('/', "\0") <=> other.path.tr('/', "\0") end |
#==(other) ⇒ Object Also known as: eql?
Compare this path with other
. The comparison is string-based. Be aware that two different paths (foo.txt
and ./foo.txt
) can refer to the same file.
92 93 94 |
# File 'lib/path/identity.rb', line 92 def == other Path === other and @path == other.path end |
#_dump(level) ⇒ Object
Marshal dumping.
144 145 146 |
# File 'lib/path/identity.rb', line 144 def _dump level @path end |
#absolute? ⇒ Boolean
Whether a path is absolute.
5 6 7 |
# File 'lib/path/predicates.rb', line 5 def absolute? is_absolute?(@path) end |
#add_extension(ext) ⇒ Object Also known as: add_ext
Adds ext
as an extension to path
. Handle both extensions with or without leading dot. No-op if ext
is empty?
.
Path('file').add_extension('txt') # => #<Path file.txt>
57 58 59 60 |
# File 'lib/path/parts.rb', line 57 def add_extension(ext) return self if ext.to_s.empty? Path.new @path + Path.dotted_ext(ext) end |
#append(contents, *open_args) ⇒ Object
Appends contents
to self
. See IO.write
or IO#write.
69 70 71 72 |
# File 'lib/path/io.rb', line 69 def append(contents, **open_args) open_args[:mode] = 'a' IO.write(@path, contents, **open_args) end |
#ascend {|path| ... } ⇒ Object Also known as: ancestors
Iterates over each element in the given path in ascending order.
Path.new('/path/to/some/file.rb').ascend { |v| p v }
#<Path /path/to/some/file.rb>
#<Path /path/to/some>
#<Path /path/to>
#<Path /path>
#<Path />
Path.new('path/to/some/file.rb').ascend { |v| p v }
#<Path path/to/some/file.rb>
#<Path path/to/some>
#<Path path/to>
#<Path path>
It doesn’t access the filesystem.
137 138 139 140 141 142 143 144 145 146 |
# File 'lib/path/parts.rb', line 137 def ascend return to_enum(:ascend) unless block_given? path = @path yield self while r = chop_basename(path) path, = r break if path.empty? yield Path.new(del_trailing_separator(path)) end end |
#atime ⇒ Object
Returns the last access time. See File.atime
.
5 6 7 |
# File 'lib/path/file.rb', line 5 def atime File.atime(@path) end |
#backfind(path) ⇒ Object
110 111 112 113 114 115 116 |
# File 'lib/path.rb', line 110 def backfind(path) condition = path[/\[(.*)\]$/, 1] || '' path = $` unless condition.empty? result = ancestors.find { |ancestor| (ancestor/path/condition).exist? } result/path if result end |
#base(*args) ⇒ Object Also known as: basename
Returns the last component of the path. See File.basename
.
15 16 17 |
# File 'lib/path/parts.rb', line 15 def base(*args) Path.new(File.basename(@path, *args)) end |
#binread(*args) ⇒ Object
Returns all the bytes from the file, or the first N
if specified. See IO.binread
.
26 27 28 |
# File 'lib/path/io.rb', line 26 def binread(*args) IO.binread(@path, *args) end |
#binwrite(contents, *open_args) ⇒ Object
Writes contents
to self
. See IO.binwrite
.
58 59 60 |
# File 'lib/path/io.rb', line 58 def binwrite(contents, *open_args) IO.binwrite(@path, contents, *open_args) end |
#blockdev? ⇒ Boolean
See File.blockdev?
.
7 8 9 |
# File 'lib/path/file_predicates.rb', line 7 def blockdev? File.blockdev?(@path) end |
#chardev? ⇒ Boolean
See File.chardev?
.
12 13 14 |
# File 'lib/path/file_predicates.rb', line 12 def chardev? File.chardev?(@path) end |
#chdir(&block) ⇒ Object
Changes the current working directory of the process to self. See Dir.chdir. The recommended way to use it is to use the block form, or not use it all!
94 95 96 |
# File 'lib/path/dir.rb', line 94 def chdir(&block) Dir.chdir(@path, &block) end |
#children(with_directory = true) ⇒ Object
Returns the children of the directory (files and subdirectories, not recursive) as an array of Path objects. The children paths are always sorted to ensure a deterministic order. By default, the returned paths will have enough information to access the files. If you set with_directory
to false
, then the returned paths will contain the filename only.
For example:
pn = Path("/usr/lib/ruby/1.8")
pn.children
# -> [ #<Path /usr/lib/ruby/1.8/English.rb>,
#<Path /usr/lib/ruby/1.8/Env.rb>,
#<Path /usr/lib/ruby/1.8/abbrev.rb>, ... ]
pn.children(false)
# -> [ #<Path English.rb>, #<Path Env.rb>, #<Path abbrev.rb>, ... ]
Note that the results never contain the entries .
and ..
in the directory because they are not children.
116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
# File 'lib/path/dir.rb', line 116 def children(with_directory=true) with_directory = false if @path == '.' result = [] Dir.foreach(@path) { |e| next if e == '.' || e == '..' if with_directory result << Path.new(@path, e) else result << Path.new(e) end } result.sort! result end |
#chmod(mode) ⇒ Object
Changes permissions of path
. See File.chmod
.
21 22 23 |
# File 'lib/path/file.rb', line 21 def chmod(mode) File.chmod(mode, @path) end |
#chmod_r(mode) ⇒ Object
Recusively changes permissions. See FileUtils.chmod_R
and File.chmod
.
88 89 90 |
# File 'lib/path/fileutils.rb', line 88 def chmod_r(mode) FileUtils.chmod_R(mode, @path) end |
#chown(owner, group) ⇒ Object
Changes the owner and group of path
. See File.chown
.
31 32 33 |
# File 'lib/path/file.rb', line 31 def chown(owner, group) File.chown(owner, group, @path) end |
#chown_r(owner, group) ⇒ Object
Recusively changes owner and group. See FileUtils.chown_R
and File.chown
.
93 94 95 |
# File 'lib/path/fileutils.rb', line 93 def chown_r(owner, group) FileUtils.chown_R(owner, group, @path) end |
#clean(consider_symlink = false) ⇒ Object Also known as: cleanpath
Returns a cleaned version 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.
18 19 20 |
# File 'lib/path/implementation.rb', line 18 def clean(consider_symlink = false) consider_symlink ? cleanpath_conservative : cleanpath_aggressive end |
#cp(to) ⇒ Object Also known as: copy
Copies the file to to
. See FileUtils.cp
.
44 45 46 47 |
# File 'lib/path/fileutils.rb', line 44 def cp(to) # TODO: remove :preserve when all implement it correctly (r31123) FileUtils.cp(@path, to, :preserve => true) end |
#cp_r(to) ⇒ Object
Copies the file or directory recursively to the directory to
. See FileUtils.cp_r
.
52 53 54 |
# File 'lib/path/fileutils.rb', line 52 def cp_r(to) FileUtils.cp_r(@path, to) end |
#ctime ⇒ Object
Returns the last change time (of the directory entry, not the file itself). See File.ctime
.
11 12 13 |
# File 'lib/path/file.rb', line 11 def ctime File.ctime(@path) end |
#descend {|path| ... } ⇒ Object
Iterates over each element in the given path in descending order.
Path.new('/path/to/some/file.rb').descend { |v| p v }
#<Path />
#<Path /path>
#<Path /path/to>
#<Path /path/to/some>
#<Path /path/to/some/file.rb>
Path.new('path/to/some/file.rb').descend { |v| p v }
#<Path path>
#<Path path/to>
#<Path path/to/some>
#<Path path/to/some/file.rb>
It doesn’t access the filesystem.
114 115 116 117 118 |
# File 'lib/path/parts.rb', line 114 def descend return to_enum(:descend) unless block_given? ascend.reverse_each { |v| yield v } nil end |
#dir ⇒ Object Also known as: dirname
31 32 33 |
# File 'lib/path/parts.rb', line 31 def dir Path.new(File.dirname(@path)) end |
#directory? ⇒ Boolean Also known as: dir?
See File.directory?
.
38 39 40 |
# File 'lib/path/file_predicates.rb', line 38 def directory? File.directory?(@path) end |
#each_child(with_directory = true) {|child| ... } ⇒ Object
Iterates over the children of the directory (files and subdirectories, not recursive). The children paths are always sorted to ensure a deterministic order. By default, the yielded paths will have enough information to access the files. If you set with_directory
to false
, then the returned paths will contain the filename only.
Path("/usr/local").each_child { |f| p f } # =>
#<Path /usr/local/share>
#<Path /usr/local/bin>
#<Path /usr/local/games>
#<Path /usr/local/lib>
#<Path /usr/local/include>
#<Path /usr/local/sbin>
#<Path /usr/local/src>
#<Path /usr/local/man>
Path("/usr/local").each_child(false) { |f| p f } # =>
#<Path share>
#<Path bin>
#<Path games>
#<Path lib>
#<Path include>
#<Path sbin>
#<Path src>
#<Path man>
157 158 159 |
# File 'lib/path/dir.rb', line 157 def each_child(with_directory=true, &b) children(with_directory).each(&b) end |
#each_entry {|entry| ... } ⇒ Object
Use #each_child instead. This method is deprecated since it is too low level and likely useless in Ruby. But it is there for the sake of compatibility with Dir.foreach and Pathname#each_entry.
Iterates over the entries (files and subdirectories) in the directory.
Path("/usr/local").each_entry { |entry| p entry } # =>
#<Path .>
#<Path ..>
#<Path lib>
#<Path share>
# ...
44 45 46 |
# File 'lib/path/dir.rb', line 44 def each_entry(&block) Dir.foreach(@path) { |f| yield Path.new(f) } end |
#each_filename {|filename| ... } ⇒ Object
Iterates over each component of the path.
Path.new("/usr/bin/ruby").each_filename { |filename| ... }
# yields "usr", "bin", and "ruby".
Returns an Enumerator if no block was given.
90 91 92 93 94 95 |
# File 'lib/path/parts.rb', line 90 def each_filename return to_enum(__method__) unless block_given? _, names = split_names(@path) names.each { |filename| yield filename } nil end |
#each_line(*args) {|line| ... } ⇒ Object Also known as: lines
Iterates over the lines in the file. See IO.foreach
.
12 13 14 |
# File 'lib/path/io.rb', line 12 def each_line(*args, &block) IO.foreach(@path, *args, &block) end |
#entries ⇒ Object
Use #children instead. This method is deprecated since it is too low level and likely useless in Ruby. But it is there for the sake of compatibility with Dir.entries (and Pathname#entries).
Return the entries (files and subdirectories) in the directory. Each Path only contains the filename. The result may contain the current directory #<Path .> and the parent directory #<Path ..>.
Path('/usr/local').entries
# => [#<Path share>, #<Path lib>, #<Path .>, #<Path ..>, <Path bin>, ...]
88 89 90 |
# File 'lib/path/dir.rb', line 88 def entries Dir.entries(@path).map(&Path) end |
#executable? ⇒ Boolean
See File.executable?
.
17 18 19 |
# File 'lib/path/file_predicates.rb', line 17 def executable? File.executable?(@path) end |
#executable_real? ⇒ Boolean
See File.executable_real?
.
22 23 24 |
# File 'lib/path/file_predicates.rb', line 22 def executable_real? File.executable_real?(@path) end |
#exist? ⇒ Boolean Also known as: exists?
See File.exist?
.
27 28 29 |
# File 'lib/path/file_predicates.rb', line 27 def exist? File.exist?(@path) end |
#expand(*args) ⇒ Object Also known as: expand_path
Expands path
, making it absolute. If the path is relative, it is expanded with the current working directory, unless dir
is given as an argument. See File.expand_path
.
112 113 114 |
# File 'lib/path/file.rb', line 112 def (*args) Path.new(File.(@path, *args)) end |
#ext ⇒ Object Also known as: extname
Returns the extension, with a leading dot. See File.extname
.
37 38 39 |
# File 'lib/path/parts.rb', line 37 def ext File.extname(@path) end |
#file? ⇒ Boolean
See File.file?
.
44 45 46 |
# File 'lib/path/file_predicates.rb', line 44 def file? File.file?(@path) end |
#find {|path| ... } ⇒ Object
Iterates over the directory tree in a depth first manner, yielding a Path 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 paths begin with a filename in the current directory, not ./
.
See Find.find
.
16 17 18 19 20 21 22 23 24 |
# File 'lib/path/find.rb', line 16 def find return to_enum(__method__) unless block_given? require 'find' if @path == '.' Find.find(@path) { |f| yield Path.new(f.sub(%r{\A\./}, '')) } else Find.find(@path) { |f| yield Path.new(f) } end end |
#fnmatch?(pattern, *args) ⇒ Boolean
Return true
if the receiver matches the given pattern. See File.fnmatch?
.
148 149 150 |
# File 'lib/path/file_predicates.rb', line 148 def fnmatch?(pattern, *args) File.fnmatch?(pattern, @path, *args) end |
#ftype ⇒ Object
Returns “type” of file (“file”, “directory”, etc). See File.ftype
.
42 43 44 |
# File 'lib/path/file.rb', line 42 def ftype File.ftype(@path) end |
#glob(pattern, flags = 0) {|path| ... } ⇒ Object
Returns or yields Path objects. Prepends the (escaped for globbing) path
to the pattern. See Dir.glob
.
69 70 71 72 73 74 75 76 |
# File 'lib/path/dir.rb', line 69 def glob(pattern, flags = 0) pattern = "#{Path.glob_escape(@path)}/#{pattern}" if block_given? Dir.glob(pattern, flags) { |f| yield Path.new(f) } else Dir.glob(pattern, flags).map(&Path) end end |
#grpowned? ⇒ Boolean
See File.grpowned?
.
33 34 35 |
# File 'lib/path/file_predicates.rb', line 33 def grpowned? File.grpowned?(@path) end |
#has_same_contents?(file) ⇒ Boolean
Whether the contents of path
and file
are identical. See FileUtils.compare_file
.
99 100 101 |
# File 'lib/path/fileutils.rb', line 99 def has_same_contents?(file) FileUtils.compare_file(@path, file) end |
#hash ⇒ Object
The hash value of the path
.
104 105 106 |
# File 'lib/path/identity.rb', line 104 def hash @path.hash end |
#head(bytes) ⇒ Object
Returns the first bytes
bytes of the file. If the file size is smaller than bytes
, return the whole contents.
91 92 93 |
# File 'lib/path/io.rb', line 91 def head(bytes) read(bytes) end |
#hidden? ⇒ Boolean
Whether this is a hidden path, i.e. starting with a dot.
35 36 37 |
# File 'lib/path/predicates.rb', line 35 def hidden? basename.to_s.start_with?('.') end |
#identical?(path) ⇒ Boolean
See File.identical?
.
140 141 142 |
# File 'lib/path/file_predicates.rb', line 140 def identical?(path) File.identical?(@path, path) end |
#init_with(coder) ⇒ Object
Psych loading.
125 126 127 128 |
# File 'lib/path/identity.rb', line 125 def init_with(coder) @path = coder['path'] init end |
#inside?(ancestor) ⇒ Boolean
Whether self
is inside ancestor
, such that ancestor
is an ancestor of self
. This is pure String manipulation. Paths should be absolute. self
is considered to be inside itself.
94 95 96 |
# File 'lib/path.rb', line 94 def inside? ancestor @path == ancestor.to_s or @path.start_with?("#{ancestor}/") end |
#inspect ⇒ Object
A representation of the path
.
114 115 116 |
# File 'lib/path/identity.rb', line 114 def inspect "#<Path #{@path}>" end |
#install(file, **options) ⇒ Object
Install file
into path
(the “prefix”, which should be a directory). If file
is not same as path/file
, replaces it. See FileUtils.install
(arguments are swapped).
83 84 85 |
# File 'lib/path/fileutils.rb', line 83 def install(file, **) FileUtils.install(file, @path, **) end |
#join(*paths) ⇒ Object
Joins paths.
path0.join(path1, ..., pathN)
# is the same as
path0 / path1 / ... / pathN
92 93 94 95 96 97 98 99 |
# File 'lib/path/implementation.rb', line 92 def join(*paths) result = nil paths.reverse_each { |path| result = Path.new(path) / result return result if result.absolute? } self / result end |
#lchmod(mode) ⇒ Object
Changes permissions of path
, not following symlink. See File.lchmod
.
26 27 28 |
# File 'lib/path/file.rb', line 26 def lchmod(mode) File.lchmod(mode, @path) end |
#lchown(owner, group) ⇒ Object
Changes the owner and group of path
, not following symlink. See File.lchown
.
37 38 39 |
# File 'lib/path/file.rb', line 37 def lchown(owner, group) File.lchown(owner, group, @path) end |
#load ⇒ Object
Path#load helps loading data from various files. JSON and YAML loaders are provided by default. See register_loader.
22 23 24 25 26 27 28 |
# File 'lib/path/load.rb', line 22 def load if LOADERS.key? ext LOADERS[ext].call(self) else raise "Unable to load #{self} (unrecognized extension)" end end |
#lstat ⇒ Object
Returns the stat of path
as a File::Stat
object, not following symlink. See File.lstat
.
72 73 74 |
# File 'lib/path/file.rb', line 72 def lstat File.lstat(@path) end |
#make_link(target) ⇒ Object
Creates a hard link to target
and returns self.
Raises Errno::EEXIST if self already exist. See File.link
(arguments are swapped).
50 51 52 53 |
# File 'lib/path/file.rb', line 50 def make_link(target) File.link(target, @path) self end |
#make_symlink(target) ⇒ Object
Creates a symbolic link to target
and returns self.
Raises Errno::EEXIST if self already exist. See File.symlink
(arguments are swapped).
85 86 87 88 |
# File 'lib/path/file.rb', line 85 def make_symlink(target) File.symlink(target, @path) self end |
#mkdir(*args) ⇒ Object
Create the referenced directory and returns self. See Dir.mkdir
.
49 50 51 52 |
# File 'lib/path/dir.rb', line 49 def mkdir(*args) Dir.mkdir(@path, *args) self end |
#mkpath ⇒ Object Also known as: mkdir_p
Creates a full path, including any intermediate directories that don’t yet exist. See FileUtils.mkpath
.
8 9 10 11 |
# File 'lib/path/fileutils.rb', line 8 def mkpath FileUtils.mkpath(@path) self end |
#mountpoint? ⇒ Boolean
Returns true
if self
points to a mountpoint.
24 25 26 27 28 29 30 31 32 |
# File 'lib/path/predicates.rb', line 24 def mountpoint? begin stat1 = lstat stat2 = parent.lstat stat1.dev != stat2.dev or stat1.ino == stat2.ino rescue Errno::ENOENT false end end |
#mtime ⇒ Object
Returns last modification time. See File.mtime
.
16 17 18 |
# File 'lib/path/file.rb', line 16 def mtime File.mtime(@path) end |
#mv(to) ⇒ Object Also known as: move
Moves self
to the to
directory.
74 75 76 77 |
# File 'lib/path/fileutils.rb', line 74 def mv(to) FileUtils.mv(@path, to) to end |
#open(*args) {|file| ... } ⇒ Object
Opens the file for reading or writing. See File.open
.
6 7 8 |
# File 'lib/path/io.rb', line 6 def open(*args, &block) File.open(@path, *args, &block) end |
#opendir {|dir| ... } ⇒ Object
See Dir.open
.
61 62 63 |
# File 'lib/path/dir.rb', line 61 def opendir(&block) Dir.open(@path, &block) end |
#outside?(ancestor) ⇒ Boolean
The opposite of #inside?.
99 100 101 |
# File 'lib/path.rb', line 99 def outside? ancestor !inside?(ancestor) end |
#owned? ⇒ Boolean
See File.owned?
.
59 60 61 |
# File 'lib/path/file_predicates.rb', line 59 def owned? File.owned?(@path) end |
#parent ⇒ Object
Returns the parent directory. This can be chained.
25 26 27 |
# File 'lib/path/implementation.rb', line 25 def parent self / '..' end |
#pipe? ⇒ Boolean
See File.pipe?
.
49 50 51 |
# File 'lib/path/file_predicates.rb', line 49 def pipe? File.pipe?(@path) end |
#pure_ext ⇒ Object
#ext without leading dot.
43 44 45 |
# File 'lib/path/parts.rb', line 43 def pure_ext Path.pure_ext(extname) end |
#read(*args) ⇒ Object
Returns all data from the file, or the first bytes
bytes if specified. See IO.read
.
19 20 21 |
# File 'lib/path/io.rb', line 19 def read(*args) IO.read(@path, *args) end |
#readable? ⇒ Boolean
See File.readable?
.
64 65 66 |
# File 'lib/path/file_predicates.rb', line 64 def readable? File.readable?(@path) end |
#readable_real? ⇒ Boolean
See File.readable_real?
.
81 82 83 |
# File 'lib/path/file_predicates.rb', line 81 def readable_real? File.readable_real?(@path) end |
#readlines(*args) ⇒ Object
Returns all the lines from the file. See IO.readlines
.
36 37 38 |
# File 'lib/path/io.rb', line 36 def readlines(*args) IO.readlines(@path, *args) end |
#readlink ⇒ Object
Reads the symbolic link. See File.readlink
.
56 57 58 |
# File 'lib/path/file.rb', line 56 def readlink Path.new(File.readlink(@path)) end |
#realdirpath(basedir = nil) ⇒ Object
Returns the real (absolute) path of self
in the actual filesystem. The real path doesn’t contain symlinks or useless dots.
The last component of the real path can be nonexistent.
130 131 132 |
# File 'lib/path/file.rb', line 130 def realdirpath(basedir=nil) Path.new(real_path_internal(false, basedir)) end |
#realpath(basedir = nil) ⇒ Object Also known as: real
Returns the real (absolute) path for self
in the actual filesystem not containing symlinks or useless dots.
All components of the path must exist when this method is called.
121 122 123 |
# File 'lib/path/file.rb', line 121 def realpath(basedir=nil) Path.new(real_path_internal(true, basedir)) end |
#relative? ⇒ Boolean
Whether a path is relative.
10 11 12 |
# File 'lib/path/predicates.rb', line 10 def relative? not absolute? end |
#relative_path_from(base_directory) ⇒ Object Also known as: relative_to, %
#relative_path_from returns a relative path from the given base_directory
to the receiver. They must be both relative or both absolute.
It doesn’t access the filesystem and assumes no symlinks.
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/path/implementation.rb', line 109 def relative_path_from(base_directory) dest = clean.path base = Path.new(base_directory).clean.path dest_prefix, dest_names = split_names(dest) base_prefix, base_names = split_names(base) unless SAME_PATHS[dest_prefix, base_prefix] raise ArgumentError, "different prefix: #{self.inspect} and #{base_directory.inspect}" end while d = dest_names.first and b = base_names.first and SAME_PATHS[d, b] dest_names.shift base_names.shift end raise ArgumentError, "base_directory has ..: #{base_directory.inspect}" if base_names.include? '..' # the number of names left in base is the ones we have to climb names = base_names.fill('..').concat(dest_names) return Path.new('.') if names.empty? Path.new(*names) end |
#relocate(from, to, new_ext = ext, &updater) ⇒ Object
Relocates this path somewhere else.
Without a block, this method is a simple shorcut for a longer expression that proves difficult to remember in practice:
to / (self.sub_ext(new_ext) % from)
That is, it relocates the original path to a target folder to
appended with the relative path from a source folder from
. An optional new extension can also be specified, as it is a common use case.
With a block, the relative path is passed to the block for user update, without the last extension. new_ext
is added after (or the original extension if not provided).
from = Path('pictures')
to = Path('output/public/thumbnails')
earth = from / 'nature/earth.jpg'
earth.relocate(from, to)
# => #<Path output/public/thumbnails/nature/earth.jpg>
earth.relocate(from, to, '.png') { |rel|
"#{rel}-200"
}
# => #<Path output/public/thumbnails/nature/earth-200.png>
145 146 147 148 149 150 151 |
# File 'lib/path.rb', line 145 def relocate(from, to, new_ext = ext, &updater) updater ||= lambda { |path| path } renamer = lambda { |rel| Path.new(updater.call(rel.rm_ext)).add_ext(new_ext) } Path.new(to) / renamer.call(self % from) end |
#rename(to) ⇒ Object
Renames the file and returns the new Path. See File.rename
.
61 62 63 64 |
# File 'lib/path/file.rb', line 61 def rename(to) File.rename(@path, to) Path.new(to) end |
#replace_extension(ext) ⇒ Object Also known as: sub_ext
Replaces the last extension of path
with ext
. Handle both extensions with or without leading dot. Removes last extension if ext
is empty?
.
Path('main.c++').replace_extension('cc') # => #<Path main.cc>
77 78 79 80 |
# File 'lib/path/parts.rb', line 77 def replace_extension(ext) return without_extension if ext.to_s.empty? Path.new(@path[0..-extname.size-1] << Path.dotted_ext(ext)) end |
#rewrite {|contents| ... } ⇒ Object
Rewrites contents of self
.
Path('file').rewrite { |contents| contents.reverse }
85 86 87 |
# File 'lib/path/io.rb', line 85 def rewrite write yield read end |
#rm ⇒ Object
Removes the file using FileUtils.rm
.
24 25 26 27 |
# File 'lib/path/fileutils.rb', line 24 def rm FileUtils.rm(@path) self end |
#rm_f ⇒ Object Also known as: safe_unlink
Removes the file, ignoring errors, using FileUtils.rm_f
.
30 31 32 33 |
# File 'lib/path/fileutils.rb', line 30 def rm_f FileUtils.rm_f(@path) self end |
#rm_rf ⇒ Object
Removes the file or directory recursively, ignoring errors, using FileUtils.rm_f
.
38 39 40 41 |
# File 'lib/path/fileutils.rb', line 38 def rm_rf FileUtils.rm_rf(@path) self end |
#rmdir ⇒ Object
Remove the referenced directory. See Dir.rmdir
.
55 56 57 |
# File 'lib/path/dir.rb', line 55 def rmdir Dir.rmdir(@path) end |
#rmtree ⇒ Object Also known as: rm_r
Deletes a directory and all beneath it. See FileUtils.rm_r
.
15 16 17 18 19 20 |
# File 'lib/path/fileutils.rb', line 15 def rmtree # The name "rmtree" is borrowed from File::Path of Perl. # File::Path provides "mkpath" and "rmtree". FileUtils.rm_r(@path) self end |
#root? ⇒ Boolean
Predicate for root directories. Returns true
if the path consists of consecutive slashes.
It doesn’t access the filesystem. So it may return false
for some paths which points to roots such as /usr/..
.
19 20 21 |
# File 'lib/path/predicates.rb', line 19 def root? is_root?(@path) end |
#setgid? ⇒ Boolean
See File.setgid?
.
91 92 93 |
# File 'lib/path/file_predicates.rb', line 91 def setgid? File.setgid?(@path) end |
#setuid? ⇒ Boolean
See File.setuid?
.
86 87 88 |
# File 'lib/path/file_predicates.rb', line 86 def setuid? File.setuid?(@path) end |
#siblings(with_directory = true) ⇒ Object
Equivalent of parent.children - [self]. Returns the siblings, the files in the same directory as the current path
. Returns only the root if path
is the root. The sibling paths are always sorted to ensure a deterministic order.
165 166 167 168 169 170 171 |
# File 'lib/path/dir.rb', line 165 def siblings(with_directory = true) if root? [self] else parent.children(with_directory) - [(with_directory ? self : basename)] end end |
#size ⇒ Object
Returns the file size in bytes. See File.size
.
77 78 79 |
# File 'lib/path/file.rb', line 77 def size File.size(@path) end |
#size? ⇒ Boolean
See File.size?
.
96 97 98 |
# File 'lib/path/file_predicates.rb', line 96 def size? File.size?(@path) end |
#socket? ⇒ Boolean
See File.socket?
.
54 55 56 |
# File 'lib/path/file_predicates.rb', line 54 def socket? File.socket?(@path) end |
#split ⇒ Object
Returns the #dirname and the #basename in an Array. See File.split
.
48 49 50 |
# File 'lib/path/parts.rb', line 48 def split File.split(@path).map(&Path) end |
#stat ⇒ Object
Returns the stat of path
as a File::Stat
object. See File.stat
.
67 68 69 |
# File 'lib/path/file.rb', line 67 def stat File.stat(@path) end |
#stem ⇒ Object
Returns the last component of the path, without the extension: base(ext)
21 22 23 |
# File 'lib/path/parts.rb', line 21 def stem base(ext) end |
#sticky? ⇒ Boolean
See File.sticky?
.
101 102 103 |
# File 'lib/path/file_predicates.rb', line 101 def sticky? File.sticky?(@path) end |
#symlink? ⇒ Boolean
See File.symlink?
.
106 107 108 |
# File 'lib/path/file_predicates.rb', line 106 def symlink? File.symlink?(@path) end |
#sysopen(*args) ⇒ Object
See IO.sysopen
.
41 42 43 |
# File 'lib/path/io.rb', line 41 def sysopen(*args) IO.sysopen(@path, *args) end |
#tail(bytes) ⇒ Object
Returns the last bytes
bytes of the file. If the file size is smaller than bytes
, return the whole contents.
97 98 99 100 101 102 103 |
# File 'lib/path/io.rb', line 97 def tail(bytes) return read if size < bytes open { |f| f.seek(-bytes, IO::SEEK_END) f.read } end |
#to_json(*args) ⇒ Object
JSON dumping.
131 132 133 134 135 136 |
# File 'lib/path/identity.rb', line 131 def to_json(*args) { 'json_class' => 'Path', 'data' => @path }.to_json(*args) end |
#to_sym ⇒ Object
Returns the path
as a Symbol.
109 110 111 |
# File 'lib/path/identity.rb', line 109 def to_sym @path.to_sym end |
#touch ⇒ Object
Updates access and modification time or create an empty file.
57 58 59 60 61 62 63 64 65 |
# File 'lib/path/fileutils.rb', line 57 def touch if exist? now = Time.now File.utime(now, now, @path) else open('w') {} end self end |
#touch! ⇒ Object
68 69 70 71 |
# File 'lib/path/fileutils.rb', line 68 def touch! dir.mkpath touch end |
#truncate(length) ⇒ Object
Truncates the file to length
bytes. See File.truncate
.
91 92 93 |
# File 'lib/path/file.rb', line 91 def truncate(length) File.truncate(@path, length) end |
#unlink ⇒ Object Also known as: delete
99 100 101 |
# File 'lib/path/file.rb', line 99 def unlink File.unlink @path end |
#uptodate?(*others) ⇒ Boolean
Returns whether self
is newer than all others
. Non-existent files are older than any file. See FileUtils.uptodate?
.
106 107 108 |
# File 'lib/path/fileutils.rb', line 106 def uptodate?(*others) FileUtils.uptodate?(@path, others) end |
#utime(atime, mtime) ⇒ Object
Updates the access and modification times. See File.utime
.
105 106 107 |
# File 'lib/path/file.rb', line 105 def utime(atime, mtime) File.utime(atime, mtime, @path) end |
#without_extension ⇒ Object Also known as: rm_ext
67 68 69 |
# File 'lib/path/parts.rb', line 67 def without_extension Path.new @path[0..-extname.size-1] end |
#world_readable? ⇒ Boolean
See File.world_readable?
.
70 71 72 |
# File 'lib/path/file_predicates.rb', line 70 def world_readable? File.world_readable?(@path) end |
#world_writable? ⇒ Boolean
See File.world_writable?
.
117 118 119 |
# File 'lib/path/file_predicates.rb', line 117 def world_writable? File.world_writable?(@path) end |
#writable? ⇒ Boolean
See File.writable?
.
111 112 113 |
# File 'lib/path/file_predicates.rb', line 111 def writable? File.writable?(@path) end |
#writable_real? ⇒ Boolean
See File.writable_real?
.
128 129 130 |
# File 'lib/path/file_predicates.rb', line 128 def writable_real? File.writable_real?(@path) end |
#write(contents, *open_args) ⇒ Object
Writes contents
to self
. See IO.write
or IO#write.
47 48 49 |
# File 'lib/path/io.rb', line 47 def write(contents, *open_args) IO.write(@path, contents, *open_args) end |
#yaml_initialize(tag, ivars) ⇒ Object
YAML loading.
119 120 121 122 |
# File 'lib/path/identity.rb', line 119 def yaml_initialize(tag, ivars) @path = ivars['path'] init end |
#zero? ⇒ Boolean Also known as: empty?
See File.zero?
. empty? is not defined in File/FileTest, but is is clearer.
134 135 136 |
# File 'lib/path/file_predicates.rb', line 134 def zero? File.zero?(@path) end |