Sha256: 3558259605c757d56ef9232c8b7229ec2faae79173c4ce7d476816ddacd8ab0f

Contents?: true

Size: 1.58 KB

Versions: 10

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true
require 'hako/env_provider'
require 'yaml'

module Hako
  module EnvProviders
    class Yaml < EnvProvider
      # @param [Pathname] root_path
      # @param [Hash<String, Object>] options
      def initialize(root_path, options)
        unless options['path']
          validation_error!('path must be set')
        end

        @yaml = YAML.load_file root_path.join(options['path'])

        unless @yaml.is_a?(Hash)
          validation_error!('Env yaml root must be Hash')
        end

        @options = options
      end

      # @param [Array<String>] variables
      # @return [Hash<String, String>]
      def ask(variables)
        env = {}
        read_from_yaml do |key, val|
          if variables.include?(key)
            env[key] = val
          end
        end
        env
      end

      private

      # @yieldparam [String] key
      # @yieldparam [String] val
      def read_from_yaml(&block)
        flatten(@yaml).each(&block)
      end

      # @param [Object] obj
      # @param [String] root
      # @param [Hash<String,String>] acc
      # @return [Hash<String, String>]
      def flatten(obj, root = nil, acc = {})
        case obj
        when Array
          ary_sep = @options.fetch('ary_sep', ',')
          acc[root] = obj.join(ary_sep)
        when Hash
          obj.each do |key, value|
            key_sep = @options.fetch('key_sep', '.')
            new_root = [root, key].reject(&:nil?).join(key_sep)
            flatten(value, new_root, acc)
          end
        else
          acc[root] = obj.to_s
        end

        acc
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
hako-0.25.2 lib/hako/env_providers/yaml.rb
hako-0.25.1 lib/hako/env_providers/yaml.rb
hako-0.25.0 lib/hako/env_providers/yaml.rb
hako-0.24.0 lib/hako/env_providers/yaml.rb
hako-0.23.0 lib/hako/env_providers/yaml.rb
hako-0.22.0 lib/hako/env_providers/yaml.rb
hako-0.21.1 lib/hako/env_providers/yaml.rb
hako-0.21.0 lib/hako/env_providers/yaml.rb
hako-0.20.3 lib/hako/env_providers/yaml.rb
hako-0.20.2 lib/hako/env_providers/yaml.rb