module EnvJson

Module containing utilities for loading a JSON file into environments variables. see {EnvJson#load_env_from_source_with_overrides}

Constants

VERSION

EnvJson version

Public Instance Methods

apply_env(configuration) click to toggle source

@!visibility private

# File lib/env_json.rb, line 44
def apply_env(configuration)
  configuration.each do |key,value|
    ENV[key] ||= value
  end
end
env() click to toggle source

return the consolidated env built by {EnvJson#load_env_from_source_with_overrides} @return [Hash] the environment variables loaded from JSON

# File lib/env_json.rb, line 22
def env
  @env or fail 'call load_env_from_source_with_overrides first'
end
generate_configuration(raw_hash, environment_name=nil, configuration={}) click to toggle source

@!visibility private

# File lib/env_json.rb, line 27
def generate_configuration(raw_hash, environment_name=nil, configuration={})
  raw_hash.inject(configuration) do |conf, (key,value)|
    next conf if key =~ /^_/

    if key == environment_name
      conf = generate_configuration(value, environment_name, conf)
    elsif not value.is_a? String and key =~ /^(test|development|staging|production)/
      # skip other environments keys
      next conf
    else
      conf[key] = value
    end
    conf
  end
end
load_env_from_source_with_overrides(json, environment_name=nil) click to toggle source

Load environments variables from a source into ENV

@param json [#read] any source that can be read by JSON.load @param environment_name [#to_str, nil] the environment name from where to take overrides @return [Hash] the loaded environment variables

# File lib/env_json.rb, line 13
def load_env_from_source_with_overrides(json, environment_name=nil)
  json = JSON.load(json)
  @env = generate_configuration(json, environment_name).tap do |configuration|
    apply_env(configuration)
  end
end