Module: YAML

Defined in:
lib/yaml_extend.rb

Overview

Extending the YAML library to allow to inherit from another YAML file(s)

Class Method Summary collapse

Class Method Details

.ext_load_file(yaml_path, inheritance_key = 'extends', extend_existing_arrays = true, config = {}) ⇒ Hash

Extended variant of the #load_file method by providing the ability to inherit from other YAML file(s)

Parameters:

  • yaml_path (String)

    the path to the yaml file to be loaded

  • inheritance_key (String|Array) (defaults to: 'extends')

    The key used in the yaml file to extend from another YAML file. Use an Array if you want to use a tree structure key like “options.extends” => [‘options’,‘extends’]

  • extend_existing_arrays (Boolean) (defaults to: true)

    extend existing arrays instead of replacing them

  • config (Hash) (defaults to: {})

    a hash to be merged into the result, usually only recursivly called by the method itself

Returns:

  • (Hash)

    the resulting yaml config



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/yaml_extend.rb', line 26

def self.ext_load_file(yaml_path, inheritance_key='extends', extend_existing_arrays=true, config = {})
  total_config ||= {}
  yaml_path = YAML.make_absolute_path yaml_path
  super_config = YAML.load_file(File.open(yaml_path))
  super_inheritance_files = yaml_value_by_key inheritance_key, super_config
  delete_yaml_key inheritance_key, super_config # we don't merge the super inheritance keys into the base yaml
  merged_config = config.clone.deeper_merge(super_config, extend_existing_arrays: extend_existing_arrays)
  if super_inheritance_files && super_inheritance_files != ''
    super_inheritance_files = [super_inheritance_files] unless super_inheritance_files.is_a? Array # we support strings as well as arrays of type string to extend from
    super_inheritance_files.each_with_index do |super_inheritance_file, index|
      super_config_path = File.dirname(yaml_path) + '/' + super_inheritance_file
      total_config = YAML.ext_load_file super_config_path, inheritance_key, extend_existing_arrays, total_config.deeper_merge(merged_config, extend_existing_arrays: extend_existing_arrays)
    end
    total_config
  else
    delete_yaml_key inheritance_key, merged_config
    merged_config
  end
end