Module: Perfgate::Config::EnvOverrides

Defined in:
lib/perfgate/config/env_overrides.rb

Overview

Applies PERFGATE_-prefixed environment variable overrides on top of a merged configuration hash, per spec section 11 ("environment- variable overrides use a documented PERFGATE_ prefix"). Any leaf path can be overridden, e.g. PERFGATE_EXECUTION_SAMPLES=12 overrides execution.samples. The override is type-coerced based on the existing default value at that path.

Constant Summary collapse

PREFIX =
"PERFGATE_"

Class Method Summary collapse

Class Method Details

.apply(hash, env: ENV) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/perfgate/config/env_overrides.rb', line 16

def apply(hash, env: ENV)
  each_leaf_path(hash) do |path, current_value|
    env_key = PREFIX + path.join("_").upcase
    next unless env.key?(env_key)

    set_path(hash, path, coerce(env[env_key], current_value))
  end
  hash
end

.coerce(raw, current_value) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/perfgate/config/env_overrides.rb', line 43

def coerce(raw, current_value)
  case current_value
  when Integer then Integer(raw)
  when Float then Float(raw)
  when true, false then %w[1 true yes on].include?(raw.downcase)
  when Array then raw.split(",").map(&:strip)
  else raw
  end
end

.each_leaf_path(hash, prefix = [], &block) ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'lib/perfgate/config/env_overrides.rb', line 26

def each_leaf_path(hash, prefix = [], &block)
  hash.each do |key, value|
    path = prefix + [key]
    if value.is_a?(Hash)
      each_leaf_path(value, path, &block)
    else
      block.call(path, value)
    end
  end
end

.set_path(hash, path, value) ⇒ Object



37
38
39
40
41
# File 'lib/perfgate/config/env_overrides.rb', line 37

def set_path(hash, path, value)
  *init, last = path
  target = init.reduce(hash) { |h, k| h[k] }
  target[last] = value
end