Module: Etna::EnvironmentVariables

Defined in:
lib/etna/environment_variables.rb

Class Method Summary collapse

Class Method Details

.deep_merge(a, b) ⇒ Object

a <- b



4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/etna/environment_variables.rb', line 4

def self.deep_merge(a, b)
  if a.is_a?(Hash)
    if b.is_a?(Hash)
      b.keys.each do |b_key|
        a[b_key] = deep_merge(a[b_key], b[b_key])
      end

      return a
    end
  end

  a.nil? ? b : a
end

.load_from_env(prefix, root: {}, env: ENV, downcase: true, sep: '__', &path_to_value_mapper) ⇒ Object



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
43
44
45
46
47
48
# File 'lib/etna/environment_variables.rb', line 18

def self.load_from_env(prefix, root: {}, env: ENV, downcase: true, sep: '__', &path_to_value_mapper)
  env.keys.each do |key|
    next unless key.start_with?(prefix + sep)

    path = key.split(sep, -1)
    path.shift
    if downcase
      path.each(&:downcase!)
    end

    result = path_to_value_mapper.call(path, env[key])
    next unless result

    path, value = result

    if path.empty?
      root = EnvironmentVariables.deep_merge(root, value)
      next
    end

    target = root
    while path.length > 1
      n = path.shift
      target = (target[n] ||= {})
    end

    target[path.last] = EnvironmentVariables.deep_merge(target[path.last], value)
  end

  root
end