Class: StandardHealth::EnvSpec

Inherits:
Object
  • Object
show all
Defined in:
lib/standard_health/env_spec.rb

Overview

DSL for declaring required and recommended environment variables.

Example:

StandardHealth::EnvSpec.define do
  required :SECRET_KEY_BASE
  required :APP_ENVIRONMENT, in: %w[staging production]
  recommended :SENTRY_DSN, description: "Error tracking DSN"
end

Each entry has:

- `name` (Symbol)
- `level` (:required | :recommended)
- `modes` (Array<String>, optional) — when set, the entry only applies
  while `APP_ENVIRONMENT` matches one of these modes. Otherwise it
  applies to every mode.
- `description` (String, optional) — human-readable hint surfaced
  verbatim by `/diagnostics/env`.

Defined Under Namespace

Classes: Entry

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeEnvSpec

Returns a new instance of EnvSpec.



40
41
42
# File 'lib/standard_health/env_spec.rb', line 40

def initialize
  @entries = []
end

Instance Attribute Details

#entriesArray<Entry> (readonly)

Returns:



33
34
35
# File 'lib/standard_health/env_spec.rb', line 33

def entries
  @entries
end

Class Method Details

.define(&block) ⇒ Object

Build a spec via the DSL.



36
37
38
# File 'lib/standard_health/env_spec.rb', line 36

def self.define(&block)
  new.tap { |spec| spec.instance_eval(&block) if block }
end

Instance Method Details

#audit(env_hash, mode:) ⇒ Array<Hash>

Run the audit against an env-like hash.

Parameters:

  • env_hash (Hash{String, Symbol => String})

    e.g. ENV.to_h

  • mode (String, Symbol)

    current APP_ENVIRONMENT value

Returns:

  • (Array<Hash>)

    one row per applicable entry, each shaped like: { name:, level:, status: :ok | :missing | :should_set, mode: }



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/standard_health/env_spec.rb', line 65

def audit(env_hash, mode:)
  mode_str = mode.to_s
  env = stringify(env_hash)

  @entries.each_with_object([]) do |entry, out|
    next unless entry.applies_to?(mode_str)

    value = env[entry.name.to_s]
    status = classify(entry, value)

    row = {
      name: entry.name,
      level: entry.level,
      status: status,
      mode: mode_str
    }
    row[:description] = entry.description if entry.description
    out << row
  end
end

Declare a recommended env var. A missing value never fails the audit; it surfaces as ‘:should_set`.



55
56
57
# File 'lib/standard_health/env_spec.rb', line 55

def recommended(name, **opts)
  add(:recommended, name, **opts)
end

#required(name, **opts) ⇒ Object

Declare a required env var.

Parameters:

  • name (Symbol, String)
  • in (Array<String>, nil)

    limit applicability to these modes

  • description (String, nil)


49
50
51
# File 'lib/standard_health/env_spec.rb', line 49

def required(name, **opts)
  add(:required, name, **opts)
end