Class: Hako::EnvProviders::Yaml

Inherits:
Hako::EnvProvider show all
Defined in:
lib/hako/env_providers/yaml.rb

Instance Method Summary collapse

Methods inherited from Hako::EnvProvider

#validation_error!

Constructor Details

#initialize(root_path, options) ⇒ Yaml

Returns a new instance of Yaml.

Parameters:

  • root_path (Pathname)
  • options (Hash<String, Object>)


11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/hako/env_providers/yaml.rb', line 11

def initialize(root_path, options)
  unless options['path']
    validation_error!('path must be set')
  end

  @yaml = YAML.load_file root_path.join(options['path'])

  unless @yaml.is_a?(Hash)
    validation_error!('Env yaml root must be Hash')
  end

  @options = options
end

Instance Method Details

#ask(variables) ⇒ Hash<String, String>

Parameters:

  • variables (Array<String>)

Returns:

  • (Hash<String, String>)


27
28
29
30
31
32
33
34
35
# File 'lib/hako/env_providers/yaml.rb', line 27

def ask(variables)
  env = {}
  read_from_yaml do |key, val|
    if variables.include?(key)
      env[key] = val
    end
  end
  env
end

#ask_keys(variables) ⇒ Array<String>

Parameters:

  • variables (Array<String>)

Returns:

  • (Array<String>)


44
45
46
47
48
49
50
51
52
# File 'lib/hako/env_providers/yaml.rb', line 44

def ask_keys(variables)
  keys = []
  read_from_yaml do |key, _|
    if variables.include?(key)
      keys << key
    end
  end
  keys
end

#can_ask_keys?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/hako/env_providers/yaml.rb', line 38

def can_ask_keys?
  true
end

#flatten(obj, root = nil, acc = {}) ⇒ Hash<String, String> (private)

Parameters:

  • obj (Object)
  • root (String) (defaults to: nil)
  • acc (Hash<String,String>) (defaults to: {})

Returns:

  • (Hash<String, String>)


66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/hako/env_providers/yaml.rb', line 66

def flatten(obj, root = nil, acc = {})
  case obj
  when Array
    ary_sep = @options.fetch('ary_sep', ',')
    acc[root] = obj.join(ary_sep)
  when Hash
    obj.each do |key, value|
      key_sep = @options.fetch('key_sep', '.')
      new_root = [root, key].reject(&:nil?).join(key_sep)
      flatten(value, new_root, acc)
    end
  else
    acc[root] = obj.to_s
  end

  acc
end

#read_from_yaml {|key, val| ... } ⇒ Object (private)

Yield Parameters:

  • key (String)
  • val (String)


58
59
60
# File 'lib/hako/env_providers/yaml.rb', line 58

def read_from_yaml(&block)
  flatten(@yaml).each(&block)
end