Class: Anyway::Env

Inherits:
Object
  • Object
show all
Includes:
Tracing
Defined in:
lib/anyway/env.rb

Overview

Parses environment variables and provides method-like access

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Tracing

capture, current_trace, current_trace_source, source_stack, trace!, trace_stack, with_trace_source

Constructor Details

#initialize(type_cast: AutoCast, env_container: ENV) ⇒ Env

Returns a new instance of Env.



31
32
33
34
35
36
# File 'lib/anyway/env.rb', line 31

def initialize(type_cast: AutoCast, env_container: ENV)
  @type_cast = type_cast
  @data = {}
  @traces = {}
  @env_container = env_container
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



29
30
31
# File 'lib/anyway/env.rb', line 29

def data
  @data
end

#env_containerObject (readonly)

Returns the value of attribute env_container.



29
30
31
# File 'lib/anyway/env.rb', line 29

def env_container
  @env_container
end

#tracesObject (readonly)

Returns the value of attribute traces.



29
30
31
# File 'lib/anyway/env.rb', line 29

def traces
  @traces
end

#type_castObject (readonly)

Returns the value of attribute type_cast.



29
30
31
# File 'lib/anyway/env.rb', line 29

def type_cast
  @type_cast
end

Class Method Details

.from_hash(hash, prefix: nil, memo: {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/anyway/env.rb', line 12

def from_hash(hash, prefix: nil, memo: {})
  hash.each do |key, value|
    prefix_with_key = (prefix && !prefix.empty?) ? "#{prefix}_#{key.to_s.upcase}" : key.to_s.upcase

    if value.is_a?(Hash)
      from_hash(value, prefix: "#{prefix_with_key}_", memo:)
    else
      memo[prefix_with_key] = value.to_s
    end
  end

  memo
end

Instance Method Details

#clearObject



38
39
40
41
# File 'lib/anyway/env.rb', line 38

def clear
  data.clear
  traces.clear
end

#fetch(prefix) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/anyway/env.rb', line 43

def fetch(prefix)
  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

#fetch_with_trace(prefix) ⇒ Object



55
56
57
# File 'lib/anyway/env.rb', line 55

def fetch_with_trace(prefix)
  [fetch(prefix), traces[prefix]]
end