Sha256: cbae634f4f3dc60219b498dd9fbbada820b7e07efcaf594159dad3e438862573

Contents?: true

Size: 963 Bytes

Versions: 4

Compression:

Stored size: 963 Bytes

Contents

# frozen_string_literal: true

require 'anyway/ext/deep_dup'
require 'anyway/ext/string_serialize'

module Anyway
  # Parses environment variables and provides
  # method-like access
  class Env
    using Anyway::Ext::DeepDup
    using Anyway::Ext::StringSerialize

    def initialize
      @data = {}
    end

    def clear
      @data.clear
    end

    def fetch(prefix)
      @data[prefix] ||= parse_env(prefix.to_s.upcase)
      @data[prefix].deep_dup
    end

    private

    def parse_env(prefix)
      ENV.each_pair.with_object({}) do |(key, val), data|
        next unless key.start_with?(prefix)

        path = key.sub(/^#{prefix}_/, '').downcase
        set_by_path(data, path, val.serialize)
      end
    end

    def set_by_path(to, path, val)
      parts = path.split("__")

      to = get_hash(to, parts.shift) while parts.length > 1

      to[parts.first] = val
    end

    def get_hash(from, name)
      (from[name] ||= {})
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
anyway_config-1.4.4 lib/anyway/env.rb
anyway_config-1.4.3 lib/anyway/env.rb
anyway_config-1.4.2 lib/anyway/env.rb
anyway_config-1.4.1 lib/anyway/env.rb