Class: AbideDevUtils::Files::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/abide_dev_utils/files.rb

Class Method Summary collapse

Class Method Details

.read(path, raw: false, safe: true, opts: {}) ⇒ 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
# File 'lib/abide_dev_utils/files.rb', line 8

def self.read(path, raw: false, safe: true, opts: {})
  AbideDevUtils::Validate.file(path)
  return File.read(path) if raw

  extension = File.extname(path)
  case extension
  when /\.yaml|\.yml/
    read_yaml(path, safe: safe, opts: opts)
  when '.json'
    require 'json'
    return JSON.parse(File.read(path), opts) if safe

    JSON.parse!(File.read(path), opts)
  when '.xml'
    require 'nokogiri'
    File.open(path, 'r') do |file|
      Nokogiri::XML.parse(file) do |config|
        config.strict.noblanks.norecover
      end
    end
  else
    File.read(path)
  end
end

.read_yaml(path, safe: true, opts: { permitted_classes: [Symbol] }) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/abide_dev_utils/files.rb', line 33

def self.read_yaml(path, safe: true, opts: { permitted_classes: [Symbol] })
  permitted_classes = opts[:permitted_classes] || [Symbol]
  if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.0.0')
    require 'psych'
    return Psych.safe_load_file(path, permitted_classes: permitted_classes) if safe

    Psych.load_file(path)
  else
    require 'yaml'
    return YAML.safe_load(File.read(path), permitted_classes) if safe

    YAML.load(File.read(path)) # rubocop:disable Security/YAMLLoad
  end
end