Class: File

Inherits:
Object show all
Defined in:
lib/more/facets/yaml.rb,
lib/core/facets/file/read.rb,
lib/core/facets/file/write.rb,
lib/core/facets/file/topath.rb

Class Method Summary collapse

Class Method Details

.append(file, str) ⇒ Object

Append to a file.

CREDIT: George Moschovitis


7
8
9
10
11
# 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) ⇒ Object

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


23
24
25
26
27
28
# 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

.nullObject

Platform dependent null device.

CREDIT: Daniel Burger


7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/core/facets/file/topath.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) ⇒ Object

Read in a file as binary data.

CREDIT: George Moschovitis


7
8
9
10
11
# File 'lib/core/facets/file/read.rb', line 7

def self.read_binary(fname)
  open(fname, 'rb') {|f|
    return f.read
  }
end

.read_list(filepath, chomp_string = '') ⇒ Object

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

CREDIT: Trans


19
20
21
22
23
24
25
26
27
# File 'lib/core/facets/file/read.rb', line 19

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 = "") ⇒ Object

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") }

CREDIT: George Moschovitis

– TODO Should it be in-place modification like this? Or would it be better if whatever the block returns is written to the file instead? ++



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/core/facets/file/write.rb', line 88

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

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

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

.rootname(file_name) ⇒ Object

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


29
30
31
32
33
34
35
36
37
# File 'lib/core/facets/file/topath.rb', line 29

def self.rootname( file_name )
  i = file_name.index('/')
  if i
    r = file_name[0...i]
    r == '' ? '/' : r
  else
    '.'
  end
end

.sanitize(filename) ⇒ Object

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

CREDIT: George Moschovitis


58
59
60
61
62
63
# File 'lib/core/facets/file/topath.rb', line 58

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

.split_all(path) ⇒ Object

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


47
48
49
50
51
52
# File 'lib/core/facets/file/topath.rb', line 47

def self.split_all(path)
  head, tail = File.split(path)
  return [tail] if head == '.' || tail == '/'
  return [head, tail] if head == '/'
  return split_all(head) + [tail]
end

.write(path, data) ⇒ Object

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


37
38
39
40
41
# 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) ⇒ Object

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


57
58
59
60
61
# 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

.yaml?(file) ⇒ Boolean

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.

Returns:

  • (Boolean)


31
32
33
34
35
36
37
38
39
# File 'lib/more/facets/yaml.rb', line 31

def self.yaml?(file)
  File.open(file) do |f|
    until f.eof?
      line = f.gets
      break true if line =~ /^---/
      break false unless line =~ /^(\s*#.*?|\s*)$/
    end
  end
end