Class: ConfLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/conf_loader.rb,
lib/conf_loader/version.rb

Overview

Helps to load conf files in salemove ecosystem

Constant Summary collapse

EnvironmentNotFoundError =
Class.new(KeyError)
ValueNotDefinedError =
Class.new(KeyError)
VERSION =
'2.1.0'

Class Method Summary collapse

Class Method Details

.check_value_presence(hash) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/conf_loader.rb', line 48

def self.check_value_presence(hash)
  error_keys = check_values_not_empty(hash)
  if error_keys.empty?
    hash
  else
    raise ValueNotDefinedError, "Undefined keys: #{error_keys.join(', ')}"
  end
end

.check_values_not_empty(hash) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/conf_loader.rb', line 57

def self.check_values_not_empty(hash)
  hash.inject([]) do |acc, (key, value)|
    errors =
      if value.is_a?(Hash)
        check_values_not_empty(value).map { |child_key| "#{key}.#{child_key}" }
      elsif value.to_s.empty?
        [key]
      else
        []
      end
    acc + errors
  end
end

.guarantee_key_presence(hash) ⇒ Object



41
42
43
44
45
46
# File 'lib/conf_loader.rb', line 41

def self.guarantee_key_presence(hash)
  hash.default_proc = proc do |h, k|
    raise KeyError, "#{k} not defined"
  end
  hash
end

.load(path, env) ⇒ Hash

Load given conf file

Returns:

  • (Hash)

    hash with symbolized keys



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/conf_loader.rb', line 22

def self.load(path, env)
  template = ERB.new File.new(path).read
  environments = YAML.load template.result(binding)

  if environments.has_key?(env)
    hash = environments[env]

    check_value_presence(
      guarantee_key_presence(Symbolizer.symbolize(hash))
    )
  else
    raise EnvironmentNotFoundError,
      "Configuration for `#{env}` not found at path #{path}"
  end
end