Class: Towel::Configuration

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

Overview

Loads and merges configuration settings for Towel.

Constant Summary collapse

FILENAMES =

Acceptable filenames in which to define Towel settings. These will be read in the defined order.

%w[Towel.toml towel.toml .Towel.toml .towel.toml].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Configuration

Creates a new configuration from a Hash.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/towel/configuration.rb', line 60

def initialize(hash = {})
  @config = {
    "auth" => {
      "account" => nil,
      "api_key" => nil
    },
    "collector" => {
      "address" => "towel.dev",
      "organization" => nil,
      "project" => nil
    },
    "labels" => {}
  }
  @config.merge!(hash)
  @config.freeze
end

Class Method Details

.readObject

Read the configuration from files and environment variables.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/towel/configuration.rb', line 9

def self.read
  # Load configuration from files, starting in the current working directory
  # and working upwards in the filesystem hierarchy until no configuration
  # files are found.
  files = []

  directory = Dir.pwd
  while true
    FILENAMES.each do |filename|
      possible_file = File.join(directory, filename)
      files << possible_file if File.exist?(possible_file)
    end

    parent = File.expand_path("..", directory)
    if directory == parent
      break
    else
      directory = parent
    end
  end

  # Combine all discovered files into one configuration.
  config = files
    .reverse
    .map { |file| TOML.load_file(file) }
    .inject({}) do |acc, toml|
      acc.merge(toml) do |key, old, new|
        case old
        when Hash then old.merge(new)
        else
          new
        end
      end
    end

  # Override with environment variables where appropriate.
  override = ->(env, section, key) do
    if ENV.key?(env)
      section_values = config[section] || {}
      section_values[key] = ENV[env]
      config[section] = section_values
    end
  end
  override.call("TOWEL_API_KEY", "auth", "api_key")
  override.call("TOWEL_ACCOUNT", "auth", "account")
  override.call("TOWEL_ADDRESS", "collector", "address")

  new(config)
end

Instance Method Details

#[](key) ⇒ Object

Retrieves a configuration section (“auth”, “collector”, “labels”, etc).



78
79
80
# File 'lib/towel/configuration.rb', line 78

def [](key)
  @config[key]
end