Sha256: fece0123610a5930dc253b9794394a26d57c42bc7dd583e67ed918adb17607ff

Contents?: true

Size: 1.68 KB

Versions: 4

Compression:

Stored size: 1.68 KB

Contents

# frozen_string_literal: true

module  Chamber
module  Keys
class   Base
  def self.resolve(**args)
    new(**args).resolve
  end

  attr_accessor :rootpath
  attr_reader   :filenames,
                :namespaces

  def initialize(rootpath:, namespaces:, filenames: nil)
    self.rootpath   = Pathname.new(rootpath)
    self.namespaces = namespaces
    self.filenames  = filenames
  end

  def resolve
    key_paths.each_with_object({}) do |path, memo|
      namespace = namespace_from_path(path) || '__default'
      value     = path.readable? ? path.read : ENV[environment_variable_from_path(path)]

      memo[namespace.downcase.to_sym] = value if value
    end
  end

  def as_environment_variables
    key_paths.select(&:readable?).each_with_object({}) do |path, memo|
      memo[environment_variable_from_path(path)] = path.read
    end
  end

  private

  def key_paths
    @key_paths = (filenames.any? ? filenames : [default_key_file_path]) +
                 namespaces.map { |n| namespace_to_key_path(n) }
  end

  # rubocop:disable Performance/ChainArrayAllocation
  def filenames=(other)
    @filenames = Array(other)
                   .map { |o| Pathname.new(o) }
                   .compact
  end
  # rubocop:enable Performance/ChainArrayAllocation

  def namespaces=(other)
    @namespaces = other + %w{signature}
  end

  def namespace_from_path(path)
    path
      .basename
      .to_s
      .match(self.class::NAMESPACE_PATTERN) { |m| m[1].upcase }
  end

  def namespace_to_key_path(namespace)
    rootpath + ".chamber.#{namespace.to_s.tr('.-', '')}#{key_filename_extension}"
  end

  def default_key_file_path
    Pathname.new(rootpath + ".chamber#{key_filename_extension}")
  end
end
end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
chamber-3.0.0rc1 lib/chamber/keys/base.rb
chamber-2.14.2 lib/chamber/keys/base.rb
chamber-2.14.1 lib/chamber/keys/base.rb
chamber-2.14.0 lib/chamber/keys/base.rb