Class: Blufin::Yml

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

Class Method Summary collapse

Class Method Details

.read_file(content_file, schema_file) ⇒ Object

Validate and initialize a YML file.

Returns:

  • Hash



7
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
# File 'lib/core/yml.rb', line 7

def self.read_file(content_file, schema_file)
    content_file = File.expand_path(content_file)
    schema_file  = File.expand_path(schema_file)
    # Check file(s) exist.
    [content_file, schema_file].each { |file| Blufin::Terminal::error("File not found: #{schema_file}") unless Blufin::Files::file_exists(file) }
    # Parse the schema file.
    begin
        schema_file_parsed = YAML.load_file(schema_file)
    rescue => e
        Blufin::Terminal::error("Failed to parse schema file: #{Blufin::Terminal::format_directory(schema_file)}", e.message)
    end
    # Initialize the validator.
    validator = Kwalify::Validator.new(schema_file_parsed)
    # Validate the content file.
    begin
        document = YAML.load_file(content_file)
        # noinspection RubyArgCount
        errors = validator.validate(document)
    rescue => e
        Blufin::Terminal::error("Failed to parse content file: #{Blufin::Terminal::format_directory(content_file)}", e.message)
    end
    # If errors occurred, display and bomb-out.
    if errors && !errors.empty?
        errors_output = []
        errors.each { |e|
            errors_output << "[#{e.path}] #{e.message}"
        }
        Blufin::Terminal::error("File had errors: #{Blufin::Terminal::format_directory(content_file)}", errors_output)
        exit
    end
    # Otherwise, return valid YML.
    document
end