Class: Configurator

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

Overview

Configurator maps lists of environment variables to names that you define in order to provide a consistent way to use configuration throughout your application

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mapping) ⇒ Configurator

Create the Configurator object

Parameters:

  • mapping (Hash)

    mapping of config names to environment value names


50
51
52
53
54
# File 'lib/configurator.rb', line 50

def initialize(mapping)
  @mapping = mapping
  @overrides = {}
  @storage = {}
end

Class Method Details

.run(mapping) ⇒ Object

Run the configurator and return the processed values

Examples:

Simple mapping

ENV['BAR'] = 'onevalue'
ENV['BAZ'] = 'another'

config = Configurator.run({
  key_one: ['FOO', 'BAR'],
  key_two: ['BAZ']
})

config.key_one
#=> 'onevalue'
config.key_two
#=> 'another'

Using override blocks

ENV['BAR'] = 'onevalue'
ENV['BAZ'] = 'another'

config = Configurator.run({
  key_one: ['FOO', 'BAR', ->(values) {
    values[:key_two]
  }],
  key_two: ['BAZ']
})

config.key_one
#=> 'another'

Parameters:

  • Hash

    map of configuration keys with array values where the array is a list of environment variables to scan for configuration

Returns:

  • OpenStruct configuration object


41
42
43
44
# File 'lib/configurator.rb', line 41

def self.run(mapping)
  reader = self.new(mapping)
  reader.read
end

Instance Method Details

#apply_overridesObject

Apply the override functions


66
67
68
69
70
# File 'lib/configurator.rb', line 66

def apply_overrides
  @overrides.each do |key, override|
    @storage[key] = override.call(@storage)
  end
end

#readOpenStruct

Perform all the required processing and return the configuration object

Returns:

  • (OpenStruct)

    configuration object


75
76
77
78
79
80
81
# File 'lib/configurator.rb', line 75

def read
  @storage = {}
  scan
  apply_overrides

  OpenStruct.new(@storage)
end

#scanObject

Process the environment variable values and store the overrides


57
58
59
60
61
62
63
# File 'lib/configurator.rb', line 57

def scan
  @mapping.each do |key, values|
    @overrides[key] = values.pop if values.last.is_a? Proc
    env_name = values.find { |v| ENV[v] }
    @storage[key] = YAML.parse(ENV[env_name]).to_ruby if env_name
  end
end