Sha256: 6165d4f7aa5d0d823f4ab23ddc5306dcea0887a67ecc64caeb95bac28d650822

Contents?: true

Size: 1.51 KB

Versions: 1

Compression:

Stored size: 1.51 KB

Contents

require 'yaml'
require 'symbolizer'
require 'erb'

# Helps to load conf files in salemove ecosystem
#
class ConfLoader
  EnvironmentNotFoundError = Class.new(KeyError)
  ValueNotDefinedError = Class.new(KeyError)

  # Load given conf file
  #
  # @path [String] path
  #   full path to conf
  # @path [String] env
  #   environment to load
  #
  # @return [Hash]
  #   hash with symbolized keys
  #
  # @api public
  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


  private_class_method

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

  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

  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
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
conf_loader-2.1.0 lib/conf_loader.rb