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.2.0'

Class Method Summary collapse

Class Method Details

.check_value_presence(hash) ⇒ Object



60
61
62
63
64
65
66
67
# File 'lib/conf_loader.rb', line 60

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



69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/conf_loader.rb', line 69

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



53
54
55
56
57
58
# File 'lib/conf_loader.rb', line 53

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



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

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

  environments = load_environments(source)

  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

.load_environments(source) ⇒ Object



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

def self.load_environments(source)
  YAML.load(source, aliases: true)
end