Class: JsonToEnv

Inherits:
Object
  • Object
show all
Defined in:
lib/json_to_env.rb

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Class Method Details

.load(json) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/json_to_env.rb', line 6

def self.load(json)
  hash = JSON.parse json
  paths = hash.keys.map { |key| [key] }
  envs = {}

  while path = paths.shift
    value = hash
    path.each { |step| value = value[step] }

    if value.respond_to?(:keys)
      value.keys.each { |key| paths << path + [key] }
    else
      envs[path.join("_").upcase] = value
    end
  end

  envs.each { |k,v| ENV[k] = self.stringify(v) unless ENV.has_key? k }
end

.load_file(file_path) ⇒ Object



32
33
34
35
36
# File 'lib/json_to_env.rb', line 32

def self.load_file(file_path)
  if File.exist? file_path
    self.load File.read(file_path)
  end
end

.stringify(v) ⇒ Object



25
26
27
28
29
30
# File 'lib/json_to_env.rb', line 25

def self.stringify(v)
  str_value = v
  str_value = JSON.dump(v) if v.is_a?(Array)
  str_value = JSON.dump(v) if v.is_a?(Hash)
  str_value.to_s
end