Class: File
- Inherits:
-
Object
- Object
- File
- Defined in:
- lib/yard/core_ext/file.rb
Constant Summary collapse
- RELATIVE_PARENTDIR =
'..'
- RELATIVE_SAMEDIR =
'.'
Manipulating Paths collapse
-
.cleanpath(path) ⇒ String
Cleans a path by removing extraneous ‘..’, ‘.’ and ‘/’ characters.
-
.relative_path(from, to) ⇒ String
Turns a path
to
into a relative path from starting pointfrom
.
Reading Files collapse
-
.open!(file, *args, &block) ⇒ Object
Forces opening a file (for writing) by first creating the file’s directory.
-
.read_binary(file) ⇒ String
Reads a file with binary encoding.
Class Method Details
.cleanpath(path) ⇒ String
Cleans a path by removing extraneous ‘..’, ‘.’ and ‘/’ characters
35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/yard/core_ext/file.rb', line 35 def self.cleanpath(path) path = path.split(SEPARATOR) path = path.inject([]) do |acc, comp| next acc if comp == RELATIVE_SAMEDIR if comp == RELATIVE_PARENTDIR && acc.size > 0 && acc.last != RELATIVE_PARENTDIR acc.pop next acc end acc << comp end File.join(*path) end |
.open!(file, *args, &block) ⇒ Object
Forces opening a file (for writing) by first creating the file’s directory
53 54 55 56 57 |
# File 'lib/yard/core_ext/file.rb', line 53 def self.open!(file, *args, &block) dir = dirname(file) FileUtils.mkdir_p(dir) unless directory?(dir) open(file, *args, &block) end |
.read_binary(file) ⇒ String
Reads a file with binary encoding
62 63 64 |
# File 'lib/yard/core_ext/file.rb', line 62 def self.read_binary(file) File.open(file, 'rb') {|f| f.read } end |
.relative_path(from, to) ⇒ String
Turns a path to
into a relative path from starting point from
. The argument from
is assumed to be a filename. To treat it as a directory, make sure it ends in File::SEPARATOR
(‘/’ on UNIX filesystems).
18 19 20 21 22 23 24 25 26 27 |
# File 'lib/yard/core_ext/file.rb', line 18 def self.relative_path(from, to) from = (from).split(SEPARATOR) to = (to).split(SEPARATOR) from.length.times do break if from[0] != to[0] from.shift; to.shift end fname = from.pop join(*(from.map { RELATIVE_PARENTDIR } + to)) end |