Class: Opto::Resolvers::Yaml

Inherits:
Opto::Resolver show all
Defined in:
lib/opto/resolvers/yaml.rb

Overview

Loads values from YAML files

Example: from:

yaml:
  file: foofoo.yml
  key: foo

Instance Attribute Summary

Attributes inherited from Opto::Resolver

#hint, #option

Instance Method Summary collapse

Methods inherited from Opto::Resolver

for, inherited, #initialize, origin, #origin, resolvers

Constructor Details

This class inherits a constructor from Opto::Resolver

Instance Method Details

#resolveObject

Raises:

  • (TypeError)

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/opto/resolvers/yaml.rb', line 17

def resolve
  raise TypeError, "Hash expected" unless hint.kind_of?(Hash)

  require 'yaml' unless Kernel.const_defined?(:YAML)

  if hint[:file]
    yaml = YAML.safe_load(::File.read(hint[:file]), [], [], true, hint[:file])
  elsif hint[:variable]
    raise TypeError, "Option not in a group" unless option.has_group?
    other_opt = option.group.option(hint[:variable])
    raise ArgumentError, "No such option: #{hint[:variable]}" if other_opt.nil?
    yaml = YAML.safe_load(other_opt.value.to_s, [], [], true, hint[:variable])
  else
    raise TypeError, "Missing file/variable definition"
  end
  if hint[:key]
    raise TypeError, "Source is not a hash" unless yaml.kind_of?(Hash)
    if yaml.key?(hint[:key])
      yaml[hint[:key]]
    elsif hint[:key].include?('.')
      yaml.dig(*hint[:key].split('.'))
    end
  else
    yaml
  end
end