Class: Philiprehberger::EnvValidator::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/env_validator/validator.rb

Overview

Validates environment variables against a schema.

Constant Summary collapse

BOOLEAN_TRUE =
%w[true 1 yes on].freeze
BOOLEAN_FALSE =
%w[false 0 no off].freeze

Instance Method Summary collapse

Constructor Details

#initialize(schema, env: ENV, prefix: nil) ⇒ Validator

Returns a new instance of Validator.

Parameters:

  • schema (Schema)

    the schema to validate against

  • env (Hash) (defaults to: ENV)

    the environment hash (default: ENV)

  • prefix (String, nil) (defaults to: nil)

    optional prefix prepended to variable names during lookup



13
14
15
16
17
# File 'lib/philiprehberger/env_validator/validator.rb', line 13

def initialize(schema, env: ENV, prefix: nil)
  @schema = schema
  @env = env
  @prefix = prefix
end

Instance Method Details

#validate!Result

Validate and return a Result.

Returns:

  • (Result)

    validated values

Raises:



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/philiprehberger/env_validator/validator.rb', line 23

def validate!
  errors = []
  values = {}

  @schema.definitions.each do |name, definition|
    value, error = resolve(name, definition)
    errors << error if error
    values[name] = value unless error
  end

  raise ValidationError, errors.join('; ') unless errors.empty?

  Result.new(values)
end