Module: ENVV::Base

Included in:
ENVV
Defined in:
lib/envv/base.rb

Instance Method Summary collapse

Instance Method Details

#build!(&rules) ⇒ ENVV

Validates ENV vars with schema rules and store coerced values in ENVV registry

Parameters:

  • A (Proc)

    block with Dry::Schema.Params rules

Returns:

Raises:



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/envv/base.rb', line 9

def build!(&rules)
  rules or raise ArgumentError, <<~MESSAGE
    A block of schema rules is required to build ENVV.
        Example:

          ENVV.build! do
            required(:MY_STRING_VAR).filled(:string)
            required(:MY_INT_VAR).filled(:integer, gt?: 3000)
            required(:MY_BOOLEAN_VAR).filled(:bool)
          end

        More info:

        - https://dry-rb.org/gems/dry-schema
        - https://github.com/16/envv

  MESSAGE

  @schema = ::Dry::Schema.Params(&rules)
  @registry = Builder.call(ENV, @schema)
  freeze
end

#fetch(key) ⇒ Object #fetch(key, default_value) ⇒ Object #fetch(key, &block) ⇒ Object

Fetch a coerced environment variable.

This method use the same signature as Hash#fetch.

Overloads:

  • #fetch(key) ⇒ Object

    Returns the value of the given ‘key` if found.

    Parameters:

    • key (String, Symbol)

    Returns:

    • the value of the given ‘key` if found.

  • #fetch(key, default_value) ⇒ Object

    Returns ‘default_value` if `key` is not found and no block was given.

    Parameters:

    • key (String, Symbol)
    • default_value

    Returns:

    • ‘default_value` if `key` is not found and no block was given

  • #fetch(key, &block) ⇒ Object

    Returns the block’s return value.

    Returns:

    • the block’s return value.

Raises:

  • (KeyError)

    if ‘key` is not found and neither `default_value` nor a block was given.



57
58
59
# File 'lib/envv/base.rb', line 57

def fetch(key, default_value = nil, &block)
  registry.fetch(key.to_s, default_value, &block)
end

#registryENVV::Registry

Returns Hash-like instance created at build.

Returns:

Raises:

  • (ENVV::NotBuilt)

    error if called before ENVV built (see #build!)



40
41
42
# File 'lib/envv/base.rb', line 40

def registry
  @registry or raise(NotBuilt)
end

#schemaDry::Schema.Params

Returns used to validate environment variables.

Returns:

  • (Dry::Schema.Params)

    used to validate environment variables

Raises:

  • (ENVV::NotBuilt)

    error if called before ENVV built (see #build!)



34
35
36
# File 'lib/envv/base.rb', line 34

def schema
  @schema
end