Class: CConfig::Config

Inherits:
Object
  • Object
show all
Includes:
HashUtils
Defined in:
lib/cconfig/cconfig.rb

Overview

Config is the main class of this library. It allows you to fetch the current configuration (after merging the values from all sources) as a hash. This has will have some specials methods: ‘::CConfig::HashUtils::Extensions#enabled?`, `::CConfig::HashUtils::Extensions#disabled?` and `::CConfig::HashUtils::Extensions#default_of`.

Instance Method Summary collapse

Constructor Details

#initialize(default:, local:, prefix:) ⇒ Config

Instantiate an object with ‘default` as the path to the default configuration, `local` as the alternate file, and `prefix` as the prefix for environment variables. The `prefix` will take “cconfig” as the default.

Note: the ‘local` value will be discarded in favor of the `#prefix_LOCAL_CONFIG_PATH` environment variable if it was set.



38
39
40
41
42
# File 'lib/cconfig/cconfig.rb', line 38

def initialize(default:, local:, prefix:)
  @default = default
  @prefix  = prefix || 'cconfig'
  @local   = ENV.fetch("#{@prefix.upcase}_LOCAL_CONFIG_PATH") { local }
end

Instance Method Details

#fetchObject

Returns a hash with the app configuration contained in it.



45
46
47
48
49
50
51
52
53
# File 'lib/cconfig/cconfig.rb', line 45

def fetch
  cfg   = File.file?(@default) ? YAML.load_file(@default) : {}
  local = fetch_local

  hsh = strict_merge_with_env(default: cfg, local: local, prefix: @prefix)
  hsh.extend(::CConfig::HashUtils::Extensions)
  hsh.defaults = cfg
  hsh
end

#to_sObject

Returns a string representation of the evaluated configuration.



56
57
58
# File 'lib/cconfig/cconfig.rb', line 56

def to_s
  hide_password(fetch.dup).to_yaml
end