Class: File
- Inherits:
-
Object
- Object
- File
- Defined in:
- lib/clir/File_extension.rb
Class Method Summary collapse
-
.affix(path) ⇒ String
extension.
-
.append(fpath, code) ⇒ Object
Add
code
to file atfpath
. -
.tail(path, nlines) ⇒ Object
whole content.
Instance Method Summary collapse
-
#tail_lines(n) ⇒ Object
Les
n
dernières lignes d’un fichier.
Class Method Details
.affix(path) ⇒ String
extension.
112 113 114 |
# File 'lib/clir/File_extension.rb', line 112 def self.affix(path) File.basename(path,File.extname(path)) end |
.append(fpath, code) ⇒ Object
Add code
to file at fpath
119 120 121 122 123 124 125 |
# File 'lib/clir/File_extension.rb', line 119 def self.append(fpath, code) begin open(fpath,'a') { |f| f.write(code) } rescue ENOENT raise "Folder #{File.dirname(fpath)} doesn't exist. Unable to write #{fpath} file." end end |
.tail(path, nlines) ⇒ Object
whole content.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/clir/File_extension.rb', line 6 def self.tail(path, nlines) file = open(path, "r") buff = 512 line_count = 0 # nlines += 1 # to get the last one file.seek(0, IO::SEEK_END) offset = file.pos # start at the end while nlines > line_count && offset > 0 to_read = if (offset - buff) < 0 offset else buff end file.seek(offset - to_read) data = file.read(to_read) data.reverse.each_char do |c| if line_count > nlines offset += 1 break end offset -= 1 if c == "\n" line_count += 1 end end end file.seek(offset) data = file.read.strip ensure file.close end |
Instance Method Details
#tail_lines(n) ⇒ Object
Returns les n
dernières lignes d’un fichier.
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/clir/File_extension.rb', line 83 def tail_lines(n) return [] if n < 1 if File.size(self) < ( 1 << 16 ) tail_buf_length = File.size(self) return self.readlines.reverse[0..n-1] else tail_buf_length = 1 << 16 end self.seek(-tail_buf_length,IO::SEEK_END) out = "" count = 0 while count <= n buf = self.read( tail_buf_length ) count += buf.count("\n") out += buf # 2 * since the pointer is a the end , of the previous iteration self.seek(2 * -tail_buf_length,IO::SEEK_CUR) end return out.split("\n")[-n..-1] end |