Class: NitroConfig::Options

Inherits:
HashWithIndifferentAccess
  • Object
show all
Defined in:
lib/nitro_config/options.rb

Overview

Representation of a config key-value tree with path-based access

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.load_yml(path, environment) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/nitro_config/options.rb', line 11

def self.load_yml(path, environment)
  erb_result = ::ERB.new(File.read(path)).result
  yaml = begin
    YAML.safe_load(erb_result, [], [], true)
  rescue ArgumentError
    YAML.safe_load(erb_result, aliases: true)
  end

  new(yaml[environment])
end

Instance Method Details

#get(path, default = nil) ⇒ Object

Returns a configuration value by path

Parameters:

  • path (String, Array)

    the path within the configuration to return, with nested keys “separated/like/this”

  • default (defaults to: nil)

    a default value to return if the path is not found in the configuration

Returns:

  • The value extracted from configuration, of the type specified when declared.



48
49
50
51
52
# File 'lib/nitro_config/options.rb', line 48

def get(path, default = nil)
  get!(path)
rescue NitroConfig::Error
  default
end

#get!(path) ⇒ Object

Returns a configuration value by path

Parameters:

  • path (String, Array)

    the path within the configuration to return, with nested keys “separated/like/this”, [‘or’, ‘like’, ‘this’]

Returns:

  • The value extracted from configuration, of the type specified when declared.

Raises:



62
63
64
65
66
67
68
69
# File 'lib/nitro_config/options.rb', line 62

def get!(path)
  split_path = path.respond_to?(:split) ? path.split(PATH_SEPARATOR) : path
  split_path.flatten.reduce(self) do |config, key|
    raise(NitroConfig::Error, path) unless config&.key?(key)

    config[key]
  end
end

#preserve! { ... } ⇒ Object

Preserves values in the global configuration which might be altered within the yielded block. This is useful for testing, where a test needs to assert behaviour with certain settings values, but you want them to be restored for the next test.

Examples:

Preserving configuration in all tests

config.around(:each) do |example|
  NitroConfig.preserve! do
    example.run
  end
end
OR
config.include NitroConfig::Rspec

Yields:

  • A block within which configuration can safely be altered, being restored on return



36
37
38
39
40
# File 'lib/nitro_config/options.rb', line 36

def preserve!
  tmp = clone
  yield
  replace(tmp)
end