Methods
Public Class methods
append( file, str )

Append to a file.

  CREDIT: George Moschovitis
# File lib/core/facets/file/write.rb, line 7
  def self.append( file, str )
    File.open( file, 'ab' ) { |f|
      f << str
    }
  end
append( file, str )

Append to a file.

  CREDIT: George Moschovitis
# File lib/core/facets/file/write.rb, line 7
  def self.append( file, str )
    File.open( file, 'ab' ) { |f|
      f << str
    }
  end
create(path, str='', &blk)

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/write.rb, line 23
  def self.create(path, str='', &blk)
    File.open(path, 'wb') do |f|
      f << str
      blk.call(f) if blk
    end
  end
create(path, str='', &blk)

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/write.rb, line 23
  def self.create(path, str='', &blk)
    File.open(path, 'wb') do |f|
      f << str
      blk.call(f) if blk
    end
  end
null()

Platform dependent null device.

  CREDIT: Daniel Burger
# File lib/core/facets/file/null.rb, line 7
  def self.null
    case RUBY_PLATFORM
    when /mswin/i
      'NUL'
    when /amiga/i
      'NIL:'
    when /openvms/i
      'NL:'
    else
      '/dev/null'
    end
  end
null()

Platform dependent null device.

  CREDIT: Daniel Burger
# File lib/core/facets/file/null.rb, line 7
  def self.null
    case RUBY_PLATFORM
    when /mswin/i
      'NUL'
    when /amiga/i
      'NIL:'
    when /openvms/i
      'NL:'
    else
      '/dev/null'
    end
  end
read_binary(fname)

Read in a file as binary data.

 CREDIT: George Moschovitis
# File lib/core/facets/file/read.rb, line 18
  def self.read_binary(fname)
    open(fname, 'rb') {|f|
      return f.read
    }
  end
read_binary(fname)

Read in a file as binary data.

 CREDIT: George Moschovitis
# File lib/core/facets/file/read.rb, line 18
  def self.read_binary(fname)
    open(fname, 'rb') {|f|
      return f.read
    }
  end
read_list(filepath, chomp_string='')

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
  def self.read_list(filepath, chomp_string='')
    farr = nil
    farr = read(filepath).split("\n")
    farr.collect! { |line|
      l = line.strip.chomp(chomp_string)
      (l.empty? or l[0,1] == '#') ? nil : l
    }
    farr.compact
  end
read_list(filepath, chomp_string='')

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
  def self.read_list(filepath, chomp_string='')
    farr = nil
    farr = read(filepath).split("\n")
    farr.collect! { |line|
      l = line.strip.chomp(chomp_string)
      (l.empty? or l[0,1] == '#') ? nil : l
    }
    farr.compact
  end
rewrite(name, mode = "") {|| ...}

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
  def self.rewrite(name, mode = "") #:yield:
    unless block_given?
      raise(ArgumentError, "Need to supply block to File.rewrite")
    end

    if mode.is_a?(Numeric) then
      flag, mode = mode, ""
      mode += "b" if flag & File::Constants::BINARY != 0
      mode += "+" if flag & File::Constants::APPEND != 0
    else
      mode.delete!("^b+")
    end

    old_str = File.open(name, "r#{mode}") { |file| file.read } #rescue ""
    old_str = str.clone

    begin
      new_str = yield(old_str)
    ensure
      if old_str != new_str
        File.open(name, "w#{mode}") { |file| file.write(new_str) }
      end
    end
  end
rewrite(name, mode = "") {|| ...}

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
  def self.rewrite(name, mode = "") #:yield:
    unless block_given?
      raise(ArgumentError, "Need to supply block to File.rewrite")
    end

    if mode.is_a?(Numeric) then
      flag, mode = mode, ""
      mode += "b" if flag & File::Constants::BINARY != 0
      mode += "+" if flag & File::Constants::APPEND != 0
    else
      mode.delete!("^b+")
    end

    old_str = File.open(name, "r#{mode}") { |file| file.read } #rescue ""
    old_str = str.clone

    begin
      new_str = yield(old_str)
    ensure
      if old_str != new_str
        File.open(name, "w#{mode}") { |file| file.write(new_str) }
      end
    end
  end
rewrite!(name, mode = "") {|| ...}

In place version of rewrite. 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
  def self.rewrite!(name, mode = "") #:yield:
    unless block_given?
      raise(ArgumentError, "Need to supply block to File.rewrite")
    end

    if mode.is_a?(Numeric) then
      flag, mode = mode, ""
      mode += "b" if flag & File::Constants::BINARY != 0
      mode += "+" if flag & File::Constants::APPEND != 0
    else
      mode.delete!("^b+")
    end

    old_str = File.open(name, "r#{mode}") { |file| file.read } #rescue ""
    new_str = str.clone

    begin
      yield(new_str)
    ensure
      if old_str != new_str
        File.open(name, "w#{mode}") { |file| file.write(str) }
      end
    end
  end
rewrite!(name, mode = "") {|| ...}

In place version of rewrite. 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
  def self.rewrite!(name, mode = "") #:yield:
    unless block_given?
      raise(ArgumentError, "Need to supply block to File.rewrite")
    end

    if mode.is_a?(Numeric) then
      flag, mode = mode, ""
      mode += "b" if flag & File::Constants::BINARY != 0
      mode += "+" if flag & File::Constants::APPEND != 0
    else
      mode.delete!("^b+")
    end

    old_str = File.open(name, "r#{mode}") { |file| file.read } #rescue ""
    new_str = str.clone

    begin
      yield(new_str)
    ensure
      if old_str != new_str
        File.open(name, "w#{mode}") { |file| file.write(str) }
      end
    end
  end
rootname(path)

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
  def self.rootname(path)
    # this should be fairly robust
    path_re = Regexp.new('[' + Regexp.escape(File::Separator + %q{\/}) + ']')

    head, tail = path.split(path_re, 2)
    return '.' if path == head
    return '/' if head.empty?
    return head
  end
rootname(path)

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
  def self.rootname(path)
    # this should be fairly robust
    path_re = Regexp.new('[' + Regexp.escape(File::Separator + %q{\/}) + ']')

    head, tail = path.split(path_re, 2)
    return '.' if path == head
    return '/' if head.empty?
    return head
  end
sanitize(filename)

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

 CREDIT: George Moschovitis
# File lib/core/facets/file/read.rb, line 7
  def self.sanitize(filename)
    filename = File.basename(filename.gsub("\\", "/")) # work-around for IE
    filename.gsub!(/[^a-zA-Z0-9\.\-\+_]/,"_")
    filename = "_#{filename}" if filename =~ /^\.+$/
    filename
  end
sanitize(filename)

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

 CREDIT: George Moschovitis
# File lib/core/facets/file/read.rb, line 7
  def self.sanitize(filename)
    filename = File.basename(filename.gsub("\\", "/")) # work-around for IE
    filename.gsub!(/[^a-zA-Z0-9\.\-\+_]/,"_")
    filename = "_#{filename}" if filename =~ /^\.+$/
    filename
  end
write(path, data)

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 37
  def self.write(path, data)
    File.open(path, "wb") do |file|
      return file.write(data)
    end
  end
write(path, data)

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 37
  def self.write(path, data)
    File.open(path, "wb") do |file|
      return file.write(data)
    end
  end
writelines(path, data)

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
  CREDIT: Gavin Sinclair
# File lib/core/facets/file/write.rb, line 57
  def self.writelines(path, data)
    File.open(path, "wb") do |file|
      file.puts(data)
    end
  end
writelines(path, data)

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
  CREDIT: Gavin Sinclair
# File lib/core/facets/file/write.rb, line 57
  def self.writelines(path, data)
    File.open(path, "wb") do |file|
      file.puts(data)
    end
  end