lib/anyway/env.rb in anyway_config-2.0.0.pre2 vs lib/anyway/env.rb in anyway_config-2.0.0.rc1

- old
+ new

@@ -2,45 +2,55 @@ module Anyway # Parses environment variables and provides # method-like access class Env + using RubyNext using Anyway::Ext::DeepDup - using Anyway::Ext::StringSerialize + using Anyway::Ext::Hash - def initialize + include Tracing + + attr_reader :data, :traces, :type_cast + + def initialize(type_cast: AutoCast) + @type_cast = type_cast @data = {} + @traces = {} end def clear - @data.clear + data.clear + traces.clear end def fetch(prefix) - @data[prefix] ||= parse_env(prefix) - @data[prefix].deep_dup + return data[prefix].deep_dup if data.key?(prefix) + + Tracing.capture do + data[prefix] = parse_env(prefix) + end.then do |trace| + traces[prefix] = trace + end + + data[prefix].deep_dup end + def fetch_with_trace(prefix) + [fetch(prefix), traces[prefix]] + end + private def parse_env(prefix) + match_prefix = "#{prefix}_" ENV.each_pair.with_object({}) do |(key, val), data| - next unless key.start_with?(prefix) + next unless key.start_with?(match_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] ||= {}) + paths = path.split("__") + trace!(:env, *paths, key: key) { data.bury(type_cast.call(val), *paths) } + end end end end