Class: App::UtilsFiles

Inherits:
Object
  • Object
show all
Defined in:
lib/core/utils_files.rb

Class Method Summary collapse

Class Method Details

.file_exists(full_path_and_file) ⇒ Object



65
66
67
# File 'lib/core/utils_files.rb', line 65

def self.file_exists(full_path_and_file)
    File.exist?(full_path_and_file)
end

.get_files_in_dir(path, only_with_extension = nil) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/core/utils_files.rb', line 73

def self.get_files_in_dir(path, only_with_extension = nil)
    path = "/#{App::UtilsStrings.remove_surrounding_slashes(File.expand_path(path))}"
    unless path_exists(path)
        raise RuntimeError, "Directory doesn't exist: #{path}"
    end
    files = Dir.glob("#{path}/**/*.#{only_with_extension.nil? ? '*' : only_with_extension}")
    files
end

.get_full_path(path) ⇒ Object



69
70
71
# File 'lib/core/utils_files.rb', line 69

def self.get_full_path(path)
    "/#{App::UtilsStrings.remove_surrounding_slashes(File.expand_path(path))}"
end

.path_exists(full_path) ⇒ Object



61
62
63
# File 'lib/core/utils_files.rb', line 61

def self.path_exists(full_path)
    File.directory?(File.expand_path(full_path))
end

.read_file(full_path_and_file) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/core/utils_files.rb', line 45

def self.read_file(full_path_and_file)

    unless file_exists(full_path_and_file)
        App::Terminal::error("The file doesn't exist: #{full_path_and_file}", nil, true)
    end

    file_content = []
    file = File.open(full_path_and_file).read
    file.gsub!(/\r\n?/, "\n")
    file.each_line do |line|
        file_content << line
    end
    file_content

end

.write_file(full_path_and_file, array_of_lines) ⇒ Object



8
9
10
11
12
13
14
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
41
42
43
# File 'lib/core/utils_files.rb', line 8

def self.write_file(full_path_and_file, array_of_lines)

    unless array_of_lines.is_a? Array
        raise RuntimeError, "Expected an array of lines to write to file, instead got: #{array_of_lines.class}"
    end

    unless path_exists(File.dirname(full_path_and_file))
        FileUtils::mkdir_p(File.dirname(full_path_and_file))
    end

    if file_exists(full_path_and_file)
        File.delete(full_path_and_file)
    end

    begin

        File.open(full_path_and_file, 'w') { |file|

            array_of_lines.each_with_index do |line, index|
                if index == array_of_lines.size - 1
                    file.write("#{line}")
                else
                    file.write("#{line}\n")
                end
            end

            file.close
        }

    rescue Exception => e

        App::Terminal::error('Something went wrong', "#{e.message}", true)

    end

end