lib/wolf_core/utils/file_utils.rb
require_relative 'logging_utils' module WolfCore module FileUtils extend WolfCore::LoggingUtils module_function def require_relative_folder(*folders) folder_files = File.join(*folders, '**', '*.rb') files_to_require = Dir[folder_files].sort # log_object files_to_require, title: 'Files to require are' safe_require(files_to_require) end def safe_require(missing_files) error_counter = {} while missing_files.any? files_to_require = missing_files missing_files = [] files_to_require.each do |file| begin # log_object "Requiring file: #{file}" require_relative file rescue NameError => e error_counter[file] = error_counter[file].to_i + 1 if error_counter[file] >= 10 log_object "Error requiring file: #{file}" log_object e, title: 'Error is' end missing_files << file if error_counter[file] < 15 end end end end def delete_files(*args) pattern = File.join(*args) files_to_delete = Dir.glob(pattern) files_to_delete.each do |file| File.delete(file) log_object "File deleted: #{file}" end log_object "File Deleting Process Finished! (#{files_to_delete.size} files deleted)" end def encode_file_to_base64_from_url(url) uri = URI.parse(url) response = Net::HTTP.get_response(uri) raise_service_error({ message: 'Failed to download file', url: url }) unless response.is_a?(Net::HTTPSuccess) encoded_file = Base64.strict_encode64(response.body) content_disposition = response['content-disposition'] filename = if content_disposition match = content_disposition.match(/filename="?([^"]+)"?/) match ? match[1] : File.basename(uri.path) else File.basename(uri.path) end log_object filename, title: 'filename is' return { filename: filename, encoded_file: encoded_file } rescue => e raise_service_error({ message: 'Failed to encode file url', encode_file_error: { message: e.message, backtrace: e.backtrace }, url: url, }) end end end