class ExtendedYAML

Constants

VERSION

Attributes

file[R]
key[R]

Public Class Methods

load(file, key: 'extends') click to toggle source

@param [String] file path to YAML file @param [String] key YAML key to use for loading files @return [Hash, Array] the parsed YAML

# File lib/extended_yaml.rb, line 12
def self.load(file, key: 'extends')
  new(file, key: key).result
end
new(file, key: 'extends') click to toggle source
# File lib/extended_yaml.rb, line 16
def initialize(file, key: 'extends')
  @file, @key = file, key
end

Public Instance Methods

evaluate() click to toggle source

@return [String] the YAML string, with evaluated and ERB

# File lib/extended_yaml.rb, line 27
def evaluate
  ERB.new(File.read file).result
end
result() click to toggle source

@return [Hash, Array, nil] the parsed YAML

# File lib/extended_yaml.rb, line 21
def result
  data = ::YAML.load evaluate
  data ? resolve_extends(data) : nil
end

Private Instance Methods

base_dir() click to toggle source
# File lib/extended_yaml.rb, line 37
def base_dir
  @base_dir ||= File.dirname file
end
expand_file_list(files) click to toggle source

Receives a string or an array of strings, each representing an acceptable path definition. Each definition may be with or without a file etxension, and may be a glob pattern. The resulting array will be a normalized list of full paths.

@param [Array, String] files one or more path definitions @return [Array] a normalized list of absolute paths

# File lib/extended_yaml.rb, line 63
def expand_file_list(files)
  list = []
  files = [files] unless files.is_a? Array

  files.each do |path|
    list += expand_path path
  end

  list
end
expand_path(path) click to toggle source

@param [String] path the path to the YAML file, with or without extension.

May include a glob pattern wildcard.

@return [Array] one or more absolute paths.

# File lib/extended_yaml.rb, line 77
def expand_path(path)
  path += extension unless path.end_with? extension
  path = File.expand_path path, base_dir
  path.include?('*') ? Dir[path] : [path]
end
extension() click to toggle source
# File lib/extended_yaml.rb, line 33
def extension
  @extension ||= File.extname file
end
resolve_extends(data) click to toggle source

@param [Hash] data the data structure, possibly with 'extends' array @return [Hash] the merged data

# File lib/extended_yaml.rb, line 43
def resolve_extends(data)
  extra_files = data.delete key
  return data unless extra_files

  extra_files = expand_file_list extra_files

  extra_files.each do |path|
    data = self.class.new(path, key: key).result.deep_merge data
  end

  data
end