module Settings::Provider

Module Provider is an inclusion for Settings::Config class.

This module used for provider validations and data normalization.

Details:

Any provider (f.e. Settings::Yaml should respond to :data and :load methods, otherwise an exception will be raised.

Any provider after provider.data method call should return non-empty hash, otherwise an exception will be raised.

Provider should present non-empty sub-hash if optional parameter “#{root}” was used. For example for root: 'data/day1', original hash needs to include subhash like:

hash = {…, …, data: {…, day1: { …, … }, … }, … }

Private Instance Methods

extract_sub_hash_from(hsh, root) click to toggle source

mutate hash unless root parameter is nil. Raise an exception if mutation result is not a valid hash.

# File lib/configurates/provider.rb, line 43
def extract_sub_hash_from(hsh, root)
  return hsh if root.nil?
  tmp = hsh
  root.split('/').each do |path|
    tmp = tmp[path.to_sym]
    msg = "No sub hash with symbol name '#{path}' for #{hsh} was found!"
    raise RootNotExist, msg unless hash_valid?(tmp)
  end
  hsh.replace tmp
end
hash_valid?(hsh) click to toggle source

valid hash is a non-empty hash object

# File lib/configurates/provider.rb, line 67
def hash_valid?(hsh)
  hsh.is_a?(Hash) && !hsh.empty? ? true : false
end
merge_storage(provider, root: nil) click to toggle source

Can be called only when Settings::Config class is initializing.

# File lib/configurates/provider.rb, line 29
def merge_storage(provider, root: nil)
  msg = "Provider #{provider} does not respond on :data or :load messages"
  raise ProviderNotRespond, msg unless provider.class.respond_to?(:load) &&
                                       provider.respond_to?(:data)

  hsh = validate_and_extract_hash_from(provider)
  extract_sub_hash_from(hsh, root)
  defined?(@root) ? @root.merge(hsh) : @root = Storage.create(hsh)
end
validate_and_extract_hash_from(provider) click to toggle source

encapsulate & extract & validate hash from provider

# File lib/configurates/provider.rb, line 57
def validate_and_extract_hash_from(provider)
  hsh = provider.data.dup
  msg = "#{hsh} is not valid or empty Hash!"
  raise HashNotValid, msg unless hash_valid?(hsh)
  hsh
end