Module: HierarchicalConfig

Defined in:
lib/hierarchical_config.rb

Defined Under Namespace

Classes: OpenStruct

Constant Summary collapse

REQUIRED =
:REQUIRED

Class Method Summary collapse

Class Method Details

.load_config(name, dir, environment) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/hierarchical_config.rb', line 45

def load_config( name, dir, environment )
  primary_config_file   = "#{dir}/#{name}.yml"
  overrides_config_file = "#{dir}/#{name}-overrides.yml"

  config_hash = load_hash_for_env( primary_config_file, environment )

  if File.exists?( overrides_config_file )
    overrides_config_hash = load_hash_for_env( overrides_config_file, environment )
    config_hash = deep_merge( config_hash, overrides_config_hash )
  end

  config_hash, errors = lock_down_and_ostructify!( config_hash, name, environment )

  raise errors.inspect unless errors.empty?

  OpenStruct.new(config_hash).freeze
end

.load_hash_for_env(file, environment) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/hierarchical_config.rb', line 63

def load_hash_for_env( file, environment )
  yaml_config   = YAML::load(ERB.new(IO.read(file)).result)

  ordered_stanza_labels = []
  ordered_stanza_labels << 'defaults' if yaml_config.key? 'defaults'
  ordered_stanza_labels += yaml_config.keys.grep(/^defaults\[.*#{environment}/).sort_by{ |a| a.count(',') }
  ordered_stanza_labels << environment if yaml_config.key? environment

  config = deep_merge_hashes_in_keys(ordered_stanza_labels, yaml_config)

  env_config_labels = []
  env_config_labels << 'env_vars' if yaml_config.key? 'env_vars'
  env_config_labels += yaml_config.keys.grep(/^env_vars\[.*#{environment}/).sort_by{ |a| a.count(',') }

  env_config = deep_merge_hashes_in_keys(env_config_labels, yaml_config)
  env_config = fill_in_env_vars(env_config)

  deep_merge(config, env_config)

rescue StandardError => e
  raise <<-ERROR
    Error loading config from file #{file}.
    #{$!.inspect}
    #{$@}
  ERROR
end