Class: Confset::Sources::EnvSource

Inherits:
Object
  • Object
show all
Defined in:
lib/confset/sources/env_source.rb

Overview

Allows settings to be loaded from a “flat” hash with string keys, like ENV.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, prefix: Confset.env_prefix || Confset.const_name, separator: Confset.env_separator, converter: Confset.env_converter, parse_values: Confset.env_parse_values) ⇒ EnvSource

Returns a new instance of EnvSource.



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/confset/sources/env_source.rb', line 12

def initialize(env,
               prefix: Confset.env_prefix || Confset.const_name,
               separator: Confset.env_separator,
               converter: Confset.env_converter,
               parse_values: Confset.env_parse_values)
  @env = env
  @prefix = prefix.to_s.split(separator)
  @separator = separator
  @converter = converter
  @parse_values = parse_values
end

Instance Attribute Details

#converterObject (readonly)

Returns the value of attribute converter.



9
10
11
# File 'lib/confset/sources/env_source.rb', line 9

def converter
  @converter
end

#parse_valuesObject (readonly)

Returns the value of attribute parse_values.



10
11
12
# File 'lib/confset/sources/env_source.rb', line 10

def parse_values
  @parse_values
end

#prefixObject (readonly)

Returns the value of attribute prefix.



7
8
9
# File 'lib/confset/sources/env_source.rb', line 7

def prefix
  @prefix
end

#separatorObject (readonly)

Returns the value of attribute separator.



8
9
10
# File 'lib/confset/sources/env_source.rb', line 8

def separator
  @separator
end

Instance Method Details

#loadObject



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
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/confset/sources/env_source.rb', line 24

def load
  return {} if @env.nil? || @env.empty?

  hash = Hash.new

  @env.each do |variable, value|
    keys = variable.to_s.split(separator)

    next if keys.shift(prefix.size) != prefix

    keys.map! { |key|
      case converter
      when :downcase then
        key.downcase
      when nil then
        key
      else
        raise "Invalid ENV variables name converter: #{converter}"
      end
    }

    begin
      leaf = keys[0...-1].inject(hash) { |h, key| h[key] ||= {} }

      if leaf.is_a?(Hash)
        leaf[keys.last] = parse_values ? __value(value) : value
      else
        conflicting_key = (prefix + keys[0...-1]).join(separator)
        Confset.logger.error("Environment variable #{variable} conflicts with variable #{conflicting_key}")
      end
    rescue IndexError
      Confset.logger.warn("Wasn't possible to parse the env variable: #{variable}")
    end
  end

  hash
end