Module: Nucleus::Adapters::FileManager
- Extended by:
- Logging
- Defined in:
- lib/nucleus/core/file_handling/file_manager.rb
Class Method Summary collapse
-
.load_file(file) ⇒ StringIO
Load the contents of the file.
-
.save_file_from_data(file, io, force = true, expected_file_md5_hex = nil) ⇒ void
Save the data from within the Data object to the file.
Methods included from Logging
configure_logger_for, log, logger_for
Class Method Details
.load_file(file) ⇒ StringIO
Load the contents of the file.
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
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 |