Module: Envin::Converter

Extended by:
Converter
Included in:
Converter
Defined in:
lib/envin/converter.rb

Instance Method Summary collapse

Instance Method Details

#build_child_split(key_split, v, coll = [], level = 0) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/envin/converter.rb', line 15

def build_child_split(key_split, v, coll=[], level=0)
  key_identifier = key_split.take(level + 1).join('-')
  lines = ""
  if !coll.include?(key_identifier) && key_split.length != level + 1
    coll << key_identifier
    lines += "#{' ' * level}#{key_split[level].downcase}:\n"
    child_line, _ = build_child_split(key_split, v,coll, level+1)
    lines += child_line
  else
    lines += "#{' ' * (key_split.length - 1) }#{key_split.last.downcase}: #{v}\n"
  end
  return lines, coll
end

#build_yaml_from_env(prefix) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/envin/converter.rb', line 29

def build_yaml_from_env prefix
  env_prefix = ENV.select{|k,v| k =~ /^#{prefix}/ }
  coll = []
  lines = ""
  Hash[env_prefix.sort].each do |key, v|
    key_split = key.split("__")
    if key_split.length == 1
      lines += "#{key.gsub(/^#{prefix}/, '').downcase}: #{v}\n"
    elsif key_split.length > 1
      key_split[0] = key_split[0].gsub(prefix, '').downcase
      child_line, coll = build_child_split(key_split, v, coll)
      lines += child_line
    end
  end

  if lines != ""
    YAML.load(lines)
  else
    return {}
  end
end

#load_yaml(file, root_element = "production") ⇒ Object



8
9
10
11
12
13
# File 'lib/envin/converter.rb', line 8

def load_yaml file, root_element="production"
  return {} if !File.exists?(file)
  file_content = ERB.new(File.read(file)).result
  content = YAML.load(file_content)
  (!root_element ? content : content[root_element]) || {}
end

#overwrite(source_file:, target_file: false, prefix:, root_element: "production") ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/envin/converter.rb', line 51

def overwrite source_file:, target_file: false , prefix:, root_element: "production"
  target_file = source_file if !target_file
  config_content = File.exist?(source_file) ? load_yaml(source_file, root_element) : {}
  config_env     = build_yaml_from_env(prefix)
  return if config_env.keys.size == 0
  root = {}
  if root_element
    root[root_element] = config_content.deep_merge(config_env)
  else
    root = config_content.merge(config_env)
  end

  File.write(target_file, YAML.dump(root))
end