Class: Yatte::FileIO

Inherits:
Object
  • Object
show all
Defined in:
lib/yatte/file_io.rb

Class Method Summary collapse

Class Method Details

.read(path) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/yatte/file_io.rb', line 5

def self.read(path)
  return [nil, "File not found: #{path}"] unless File.exist?(path)
  return [nil, "Permission denied: #{path}"] unless File.readable?(path)

  content = File.read(path, encoding: "UTF-8")
  lines = content.lines.map { |line| +line.chomp }
  lines = [+""] if lines.empty?
  [lines, nil]
rescue SystemCallError => e
  [nil, e.message]
end

.write(path, content) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/yatte/file_io.rb', line 17

def self.write(path, content)
  tmp_path = "#{path}.tmp"
  bytes = content.bytesize

  File.write(tmp_path, content)
  File.rename(tmp_path, path)
  [true, "#{bytes} bytes written to disk"]
rescue SystemCallError => e
  [false, e.message]
ensure
  File.delete(tmp_path) if tmp_path && File.exist?(tmp_path)
end