Class: Leash::Env

Inherits:
Object
  • Object
show all
Defined in:
lib/leash/env.rb

Overview

‘leash.env` namespace — runtime env-var fetcher with a per-instance 60 s TTL cache. Mirrors the TS `leash.env.get` / `leash.env.getMany` surface and the Python `EnvNamespace` behaviour (`Optional` — Ruby returns `nil` for HTTP 404 instead of raising, so callers can branch naturally).

Defined Under Namespace

Classes: NoApiKeyError

Constant Summary collapse

CACHE_TTL_S =
60

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(platform_url:, api_key:, transport:) ⇒ Env

Returns a new instance of Env.



18
19
20
21
22
23
# File 'lib/leash/env.rb', line 18

def initialize(platform_url:, api_key:, transport:)
  @platform_url = platform_url.to_s.sub(%r{/+\z}, "")
  @api_key = api_key
  @transport = transport
  @cache = {}
end

Instance Attribute Details

#platform_urlObject (readonly)

Returns the value of attribute platform_url.



16
17
18
# File 'lib/leash/env.rb', line 16

def platform_url
  @platform_url
end

Instance Method Details

#clear_cache!Object



56
57
58
# File 'lib/leash/env.rb', line 56

def clear_cache!
  @cache.clear
end

#get(key, fresh: false) ⇒ String?

Resolve a single env-var value.

Parameters:

  • key (String)

    the env-var name (uppercase by convention)

  • fresh (Boolean) (defaults to: false)

    skip the TTL cache for this call; the freshly fetched value is still written back to the cache

Returns:

  • (String, nil)

    the value, or ‘nil` when the platform reports the key as not declared / not found

Raises:

  • (Leash::Error)

    for auth / invalid-key / plan / platform errors



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/leash/env.rb', line 33

def get(key, fresh: false)
  now = monotonic_now
  unless fresh
    entry = @cache[key]
    return entry[:value] if entry && entry[:expires_at] > now
  end

  value = fetch_one(key)
  @cache[key] = { value: value, expires_at: now + CACHE_TTL_S }
  value
end

#get_many(keys) ⇒ Hash{String => String, nil}

Bulk variant — resolve multiple keys sequentially against the shared TTL cache.

Returns:

  • (Hash{String => String, nil})


49
50
51
52
53
# File 'lib/leash/env.rb', line 49

def get_many(keys)
  result = {}
  keys.each { |k| result[k] = get(k) }
  result
end