Parent

File

Public Class Methods

append( file, str ) click to toggle source

Append to a file.

CREDIT: George Moschovitis

    # File lib/core/facets/file/append.rb, line 7
 7:   def self.append( file, str )
 8:     File.open( file, 'ab' ) { |f|
 9:       f << str
10:     }
11:   end
create(path, str='', &blk) click to toggle source

Creates a new file, or overwrites an existing file, and writes a string into it. Can also take a block just like File#open, which is yielded after the string is writ.

  str = 'The content for the file'
  File.create('myfile.txt', str)

CREDIT: George Moschovitis

    # File lib/core/facets/file/create.rb, line 13
13:   def self.create(path, str='', &blk)
14:     open(path, 'wb') do |f|
15:       f << str
16:       blk.call(f) if blk
17:     end
18:   end
ext(filename, new_ext=nil) click to toggle source

Takes a file name string and returns or changes its extension.

Without a new extension argument, returns the extension of the file name. In this respect # is like #, but unlike # it does not include the dot prefix.

With a new extension argument, changes the exension of the file name to the new extension and returns it.

Examples:

  File.ext('file.rb')          => 'rb'
  File.ext('file.rb', 'txt')   => 'file.txt'
  File.ext('file.rb', '.txt')  => 'file.txt'
  File.ext('file.rb', '')      => 'file'

This method can be used with String#file for more object-oriented notation.

  'file.rb'.file.ext('txt')   => 'file.txt'

CREDIT: Lavir the Whiolet

    # File lib/core/facets/file/ext.rb, line 25
25:   def self.ext(filename, new_ext=nil)
26:     old_ext = extname(filename)
27:     if new_ext == nil
28:       old_ext.sub(/^\./, '')
29:     else
30:       new_ext = '.' + new_ext unless (new_ext.empty? || new_ext[0,1] == '.')
31:       filename.chomp(old_ext) + new_ext
32:     end
33:   end
null() click to toggle source

Platform dependent null device.

CREDIT: Daniel Burger

    # File lib/core/facets/file/null.rb, line 7
 7:   def self.null
 8:     case RUBY_PLATFORM
 9:     when /mswin/
10:       'NUL'
11:     when /amiga/
12:       'NIL:'
13:     when /openvms/
14:       'NL:'
15:     else
16:       '/dev/null'
17:     end
18:   end
read_binary(fname) click to toggle source

Read in a file as binary data.

CREDIT: George Moschovitis

    # File lib/core/facets/file/read.rb, line 18
18:   def self.read_binary(fname)
19:     open(fname, 'rb') {|f|
20:       return f.read
21:     }
22:   end
read_list(filepath, chomp_string='') click to toggle source

Reads in a file, removes blank lines and remarks (lines starting with ’#’) and then returns an array of all the remaining lines.

CREDIT: Trans

    # File lib/core/facets/file/read.rb, line 30
30:   def self.read_list(filepath, chomp_string='')
31:     farr = nil
32:     farr = read(filepath).split("\n")
33:     farr.collect! { |line|
34:       l = line.strip.chomp(chomp_string)
35:       (l.empty? or l[0,1] == '#') ? nil : l
36:     }
37:     farr.compact
38:   end
rewrite(name, mode = "") click to toggle source

Opens a file as a string and writes back the string to the file at the end of the block.

Returns the number of written bytes or nil if the file wasn’t modified.

Note that the file will even be written back in case the block raises an exception.

Mode can either be “b” or “+” and specifies to open the file in binary mode (no mapping of the plattform’s newlines to “n“ is done) or to append to it.

  # Reverse contents of "message"
  File.rewrite("message") { |str| str.reverse }

  # Replace "foo" by "bar" in "binary"
  File.rewrite("binary", "b") { |str| str.gsub("foo", "bar") }

IMPORTANT: The old version of this method required in place modification of the file string. The new version will write whatever the block returns instead!!!

CREDIT: George Moschovitis

    # File lib/core/facets/file/rewrite.rb, line 28
28:   def self.rewrite(name, mode = "") #:yield:
29:     unless block_given?
30:       raise(ArgumentError, "Need to supply block to File.rewrite")
31:     end
32: 
33:     if mode.is_a?(Numeric) then
34:       flag, mode = mode, ""
35:       mode += "b" if flag & File::Constants::BINARY != 0
36:       mode += "+" if flag & File::Constants::APPEND != 0
37:     else
38:       mode.delete!("^b+")
39:     end
40: 
41:     old_str = open(name, "r#{mode}") { |file| file.read } #rescue ""
42:     old_str = old_str.clone
43: 
44:     begin
45:       new_str = yield(old_str)
46:     ensure
47:       if old_str != new_str
48:         open(name, "w#{mode}") { |file| file.write(new_str) }
49:       end
50:     end
51:   end
rewrite!(name, mode = "") click to toggle source

In place version of #. This version of method requires that the string be modified in place within the block.

  # Reverse contents of "message"
  File.rewrite("message") { |str| str.reverse! }

  # Replace "foo" by "bar" in "binary"
  File.rewrite("binary", "b") { |str| str.gsub!("foo", "bar") }
    # File lib/core/facets/file/rewrite.rb, line 62
62:   def self.rewrite!(name, mode = "") #:yield:
63:     unless block_given?
64:       raise(ArgumentError, "Need to supply block to File.rewrite")
65:     end
66: 
67:     if mode.is_a?(Numeric) then
68:       flag, mode = mode, ""
69:       mode += "b" if flag & File::Constants::BINARY != 0
70:       mode += "+" if flag & File::Constants::APPEND != 0
71:     else
72:       mode.delete!("^b+")
73:     end
74: 
75:     old_str = open(name, "r#{mode}") { |file| file.read } #rescue ""
76:     new_str = old_str.clone
77: 
78:     begin
79:       yield(new_str)
80:     ensure
81:       if old_str != new_str
82:         open(name, "w#{mode}") { |file| file.write(str) }
83:       end
84:     end
85:   end
rootname(path) click to toggle source

Returns onlt the first portion of the directory of a file path name.

  File.rootname('lib/jump.rb')  #=> 'lib'
  File.rootname('/jump.rb')     #=> '/'
  File.rootname('jump.rb')      #=> '.'

CREDIT: Trans

    # File lib/core/facets/file/rootname.rb, line 12
12:   def self.rootname(path)
13:     # this should be fairly robust
14:     path_re = Regexp.new('[' + Regexp.escape(File::Separator + %{\/}) + ']')
15: 
16:     head, tail = path.split(path_re, 2)
17:     return '.' if path == head
18:     return '/' if head.empty?
19:     return head
20:   end
sanitize(filename) click to toggle source

Cleans up a filename to ensure it will work on filesystem.

CREDIT: George Moschovitis

    # File lib/core/facets/file/read.rb, line 7
 7:   def self.sanitize(filename)
 8:     filename = File.basename(filename.gsub("\\", "/")) # work-around for IE
 9:     filename.gsub!(/[^a-zA-Z0-9\.\-\+_]/,"_")
10:     filename = "_#{filename}" if filename =~ /^\.+$/
11:     filename
12:   end
split_all(path) click to toggle source

Splits a file path into an array of individual path components. This differs from File.split, which divides the path into only two parts, directory path and basename.

  File.split_all("a/b/c") =>  ['a', 'b', 'c']

CREDIT: Trans

    # File lib/core/facets/file/split_all.rb, line 11
11:   def self.split_all(path)
12:     head, tail = File.split(path)
13:     return [tail] if head == '.' || tail == '/'
14:     return [head, tail] if head == '/'
15:     return split_all(head) + [tail]
16:   end
split_root(path) click to toggle source

Return the head of path from the rest of the path.

  File.split_root('etc/xdg/gtk')  #=> ['etc', 'xdg/gtk']
    # File lib/core/facets/file/split_root.rb, line 7
 7:   def self.split_root(path)
 8:     path_re = Regexp.new('[' + Regexp.escape(File::Separator + %{\/}) + ']')
 9:     path.split(path_re, 2)
10:   end
write(path, data) click to toggle source

Writes the given data to the given path and closes the file. This is done in binary mode, complementing IO.read in standard Ruby.

Returns the number of bytes written.

CREDIT: Gavin Sinclair

    # File lib/core/facets/file/write.rb, line 15
15:   def self.write(path, data)
16:     File.open(path, "wb") do |file|
17:       return file.write(data)
18:     end
19:   end
writelines(path, data) click to toggle source

Writes the given array of data to the given path and closes the file. This is done in binary mode, complementing IO.readlines in standard Ruby.

Note that readlines (the standard Ruby method) returns an array of lines with newlines intact, whereas writelines uses puts, and so appends newlines if necessary. In this small way, readlines and writelines are not exact opposites.

Returns nil.

CREDIT: Noah Gibbs, Gavin Sinclair

    # File lib/core/facets/file/writelines.rb, line 16
16:   def self.writelines(path, data)
17:     File.open(path, "wb") do |file|
18:       file.puts(data)
19:     end
20:   end
yaml?(file) click to toggle source

Is a file a YAML file?

Note this isn’t perfect. At present it depends on the use use of an initial document separator (eg. ’—’). With YAML 1.1 the %YAML delaration will be manditory, so in the future this can be adapted to fit that standard.

    # File lib/more/facets/yaml.rb, line 65
65:   def self.yaml?(file)
66:     File.open(file) do |f|
67:       until f.eof?
68:         line = f.gets
69:         break true if line =~ /^---/
70:         break false unless line =~ /^(\s*#.*?|\s*)$/
71:       end
72:     end
73:   end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.