Class: ReVIEW::YAMLLoader

Inherits:
Object show all
Defined in:
lib/review/yamlloader.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.safe_load(s) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/review/yamlloader.rb', line 25

def self.safe_load(s)
  if YAML.respond_to?(:safe_load_file)
    YAML.safe_load(s, aliases: true, permitted_classes: [Date])
  else
    begin
      # < Ruby 3.1
      YAML.safe_load(s, aliases: true, permitted_classes: [Date])
    rescue ArgumentError, Psych::DisallowedClass
      # < Ruby 2.7
      YAML.safe_load(s, [Date])
    end
  end
end

.safe_load_file(file) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/review/yamlloader.rb', line 6

def self.safe_load_file(file)
  if YAML.respond_to?(:safe_load_file)
    YAML.safe_load_file(file, aliases: true, permitted_classes: [Date])
  else
    File.open(file, 'rt:bom|utf-8') do |f|
      begin
        # < Ruby 3.1
        YAML.safe_load(f, filename: file, aliases: true, permitted_classes: [Date])
      rescue ArgumentError
        # < Ruby 2.7
        YAML.safe_load(f, [Date])
      rescue Psych::DisallowedClass
        # < Ruby 2.5
        YAML.safe_load(File.read(file), [Date])
      end
    end
  end
end

Instance Method Details

#load_file(yamlfile) ⇒ Object

load YAML files

‘inherit: [3.yml, 6.yml]` in 7.yml; `inherit: [1.yml, 2.yml]` in 3.yml; `inherit: [4.yml, 5.yml]` in 6.yml

=> 7.yml > 6.yml > 5.yml > 4.yml > 3.yml > 2.yml > 1.yml


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/review/yamlloader.rb', line 44

def load_file(yamlfile)
  file_queue = [File.expand_path(yamlfile)]
  loaded_files = {}
  yaml = {}

  while file_queue.present?
    current_file = file_queue.shift
    current_yaml = YAMLLoader.safe_load_file(current_file)
    if current_yaml.instance_of?(FalseClass) || current_yaml.nil?
      raise "#{File.basename(current_file)} is malformed."
    end

    yaml = current_yaml.deep_merge(yaml)

    if yaml.key?('inherit')
      inherit_files = parse_inherit(yaml, yamlfile, loaded_files)
      file_queue = inherit_files + file_queue
    end
  end

  yaml
end

#parse_inherit(yaml, yamlfile, loaded_files) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/review/yamlloader.rb', line 67

def parse_inherit(yaml, yamlfile, loaded_files)
  files = []

  yaml['inherit'].reverse_each do |item|
    inherit_file = File.expand_path(item, File.dirname(yamlfile))

    # Check loop
    if loaded_files[inherit_file]
      raise "Found circular YAML inheritance '#{inherit_file}' in #{yamlfile}."
    end

    loaded_files[inherit_file] = true
    files << inherit_file
  end

  yaml.delete('inherit')

  files
end