Sha256: 4c5d4a61f8675ff8460d54ac7e579c1fab4f137f1709463f51e87b75bb1bb668

Contents?: true

Size: 1.34 KB

Versions: 15

Compression:

Stored size: 1.34 KB

Contents

# frozen_string_literal: true

require 'yaml'
require 'active_support/core_ext/hash'

module Checkoff
  # Use the provided config from a YAML file, and fall back to env
  # variable if it's not populated for a key'
  class EnvFallbackConfigLoader
    def initialize(config, sym, yaml_filename)
      @config = config
      @envvar_prefix = sym.upcase
      @yaml_filename = yaml_filename
    end

    def [](key)
      config_value = @config[key]
      return config_value unless config_value.nil?

      ENV[envvar_name(key)]
    end

    def fetch(key)
      out = self[key]
      return out unless out.nil?

      raise KeyError,
            "Please configure either the #{key} key in #{@yaml_filename} or set #{envvar_name(key)}"
    end

    private

    def envvar_name(key)
      "#{@envvar_prefix}__#{key.upcase}"
    end
  end

  # Load configuration file
  class ConfigLoader
    class << self
      def load(sym)
        yaml_result = load_yaml_file(sym)
        EnvFallbackConfigLoader.new(yaml_result, sym, yaml_filename(sym))
      end

      private

      def load_yaml_file(sym)
        filename = yaml_filename(sym)
        return {} unless File.exist?(filename)

        YAML.load_file(filename).with_indifferent_access
      end

      def yaml_filename(sym)
        file = "#{sym}.yml"
        File.expand_path("~/.#{file}")
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
checkoff-0.17.0 lib/checkoff/config_loader.rb
checkoff-0.16.1 lib/checkoff/config_loader.rb
checkoff-0.16.0 lib/checkoff/config_loader.rb
checkoff-0.15.2 lib/checkoff/config_loader.rb
checkoff-0.15.1 lib/checkoff/config_loader.rb
checkoff-0.15.0 lib/checkoff/config_loader.rb
checkoff-0.14.1 lib/checkoff/config_loader.rb
checkoff-0.14.0 lib/checkoff/config_loader.rb
checkoff-0.13.2 lib/checkoff/config_loader.rb
checkoff-0.13.1 lib/checkoff/config_loader.rb
checkoff-0.13.0 lib/checkoff/config_loader.rb
checkoff-0.12.1 lib/checkoff/config_loader.rb
checkoff-0.12.0 lib/checkoff/config_loader.rb
checkoff-0.11.1 lib/checkoff/config_loader.rb
checkoff-0.11.0 lib/checkoff/config_loader.rb