Module: Nucleus::Adapters::FileManager

Extended by:
Logging
Defined in:
lib/nucleus/core/file_handling/file_manager.rb

Class Method Summary collapse

Methods included from Logging

configure_logger_for, log, logger_for

Class Method Details

.load_file(file) ⇒ StringIO

Load the contents of the file.

Parameters:

  • file (String)

    absolute path of the file to read

Returns:

  • (StringIO)

    binary contents of the file, rewinded

Raises:



10
11
12
13
14
15
16
17
18
# File 'lib/nucleus/core/file_handling/file_manager.rb', line 10

def self.load_file(file)
  io = StringIO.new('')
  File.open(file, 'r') do |opened_file|
    opened_file.binmode
    io.write opened_file.read
  end
  io.rewind
  io
end

.save_file_from_data(file, io, force = true, expected_file_md5_hex = nil) ⇒ void

This method returns an undefined value.

Save the data from within the Data object to the file. By default, this replaces already existing files. If force is set to false, the method call will fail if there already is a file at the destination. If force is false, but expected_file_md5_hex is specified, the file will be replaced as long as the hexdigest of the current file is equal to the expected_file_md5_hex param.

If nil, file is not replaced as long as force == false in the repository

Parameters:

  • file (String)

    absolute path of the file to write to

  • io (Data)

    data to write to the file

  • force (Boolean) (defaults to: true)

    if true file is replaced, else write fails

  • expected_file_md5_hex (String) (defaults to: nil)

    MD5 hexdigest of the expected file to be replaced.

Raises:

  • (Nucleus::FileExistenceError)

    if the file already existed

  • (ArgumentError)

    if expected_file_md5_hex did not match the MD5 hexdigest of the current file



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/nucleus/core/file_handling/file_manager.rb', line 35

def self.save_file_from_data(file, io, force = true, expected_file_md5_hex = nil)
  if File.exist? file
    unless force
      # fail if file exists, but shall not be replaced
      fail Nucleus::FileExistenceError, 'File already exists' if expected_file_md5_hex.nil?

      # do only replace if file is as expected
      actual_hex = Digest::MD5.file(file).hexdigest
      unless actual_hex == expected_file_md5_hex
        fail ArgumentError, "File to replace does exist, but hash sum is different than expected: #{actual_hex}"
      end
    end
  end

  # rewind IO
  io.rewind if io.respond_to? :rewind

  # create parent directory
  dirname = File.dirname(file)
  FileUtils.mkdir_p(dirname) unless File.directory?(dirname)

  # write file and replace existing
  File.open(file, 'w') do |opened_file|
    opened_file.binmode
    opened_file.write io.read
  end
end