Class: Germinate::SourceFile

Inherits:
Object
  • Object
show all
Defined in:
lib/germinate/source_file.rb

Overview

SourcePath represents an article source file on disk.

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ SourceFile

Returns a new instance of SourceFile.



11
12
13
# File 'lib/germinate/source_file.rb', line 11

def initialize(path)
  @path = Pathname(path)
end

Instance Method Details

#write!(lines) ⇒ Object



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
# File 'lib/germinate/source_file.rb', line 15

def write!(lines)
  log.debug "Writing #{lines.size} lines to #{path}"
  file = File.new(path)
  flock_result = file.flock(File::LOCK_EX)
  if flock_result != 0
    raise "Unable to lock file #{path}"
  end
  FileUtils.cp(path, backup_path)
  unless path.read == backup_path.read
    raise "Error backup up #{path} to #{backup_path}"
  end
  begin
    path.open('w+') do |output|
      lines.each do |line|
        output.write(line)
      end
    end
  rescue Exception => error
    FileUtils.cp(backup_path, path)
    raise
  end
  log.info "Changes saved to #{path}."
  log.info "Previous state saved as #{backup_path}."
ensure
  file.flock(File::LOCK_UN)
end