Class: File
- Inherits:
-
Object
- Object
- File
- Defined in:
- lib/yard/core_ext/file.rb
Constant Summary
- RELATIVE_PARENTDIR =
'..'- RELATIVE_SAMEDIR =
'.'
Class Method Summary
- + (String) cleanpath(path) Cleans a path by removing extraneous ’..’, ’.’ and ’/’ characters.
- + (Object) open!(file, *args, &block) Forces opening a file (for writing) by first creating the file’s directory.
- + (String) read_binary(file) Reads a file with binary encoding.
- + (String) relative_path(from, to) Turns a path to into a relative path from starting point from.
Class Method Details
+ (String) cleanpath(path)
Cleans a path by removing extraneous ’..’, ’.’ and ’/’ characters
33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/yard/core_ext/file.rb', line 33 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.pop next acc end acc << comp end File.join(*path) end |
+ (Object) open!(file, *args, &block)
Forces opening a file (for writing) by first creating the file’s directory
47 48 49 50 51 |
# File 'lib/yard/core_ext/file.rb', line 47 def self.open!(file, *args, &block) dir = dirname(file) FileUtils.mkdir_p(dir) unless directory?(dir) open(file, *args, &block) end |
+ (String) read_binary(file)
Reads a file with binary encoding
55 56 57 |
# File 'lib/yard/core_ext/file.rb', line 55 def self.read_binary(file) File.open(file, 'rb') {|f| f.read } end |
+ (String) relative_path(from, to)
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).
16 17 18 19 20 21 22 23 24 25 |
# File 'lib/yard/core_ext/file.rb', line 16 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 |