Module: Deepenv

Defined in:
lib/deepenv.rb,
lib/deepenv/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.3"

Class Method Summary collapse

Class Method Details

.parse_env_value(val_in) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/deepenv.rb', line 30

def parse_env_value(val_in) 
  val = val_in.strip
  if /^ +$/ =~ val_in then  # if one ore more whitespaces only, assume it's on purpose
    val_in
  elsif val === '' then     # blank goes to nil
    nil
  elsif val === 'null' then # return null as string so as not to be parsed by json later
    val 
  elsif /^\d+\.\d+$/ =~ val
    val.to_f
  elsif /^\d+$/ =~ val
    val.to_i
  elsif /^true$/i =~ val
    true
  elsif /^false$/i =~ val
    false
  else 
    begin
      JSON.parse(val)
    rescue
      val
    end
  end
end

.to_config(original = {}, opts = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/deepenv.rb', line 11

def to_config (original={}, opts={})
  @@prefix = opts.fetch(:prefix, "DEEPENV_")
  @@nesting_delimiter = opts.fetch(:nesting_delimiter, '__').downcase

  ENV.filter {|k| k.start_with? @@prefix}
  .map {|k, v| [k, parse_env_value(v)]}
  .each_with_object(
    original.deep_dup()
  ) do |kv,hash| 
    hash.deep_set(
        kv[0].dup
          .downcase!
          .sub(/^#{Regexp.escape(@@prefix.downcase)}/, '') 
          .split(@@nesting_delimiter).map(&:to_sym),
        kv[1]
      ) 
  end
end