Class: ConfigX::UntypedConfig

Inherits:
OpenStruct
  • Object
show all
Includes:
Configurable
Defined in:
lib/config_x/untyped_config.rb

Overview

The Config class extends OpenStruct to provide a flexible configuration object.

Instance Method Summary collapse

Methods included from Configurable

#with_fallback

Constructor Details

#initialize(members) ⇒ UntypedConfig

Returns a new instance of UntypedConfig.

Parameters:

  • members (Hash)

    the initial configuration hash

Raises:

  • (ArgumentError)

    if any of the keys are not convertible to strings



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/config_x/untyped_config.rb', line 12

def initialize(members)
  super({})

  members.each do |key, value|
    raise ArgumentError, "option keys should be strings" unless key.respond_to?(:to_s)

    key = key.to_s

    if value.is_a?(Hash)
      value = self.class.new(value)
    elsif value.is_a?(Array)
      value = value.map do |element|
        element.is_a?(Hash) ? self.class.new(element) : element
      end
    end

    self[key] = value
  end

  freeze
end

Instance Method Details

#to_hHash

Converts the Config object to a hash.

Returns:

  • (Hash)

    the configuration as a hash



37
38
39
40
41
# File 'lib/config_x/untyped_config.rb', line 37

def to_h
  each_pair.each_with_object({}) do |(key, value), hash|
    hash[key] = value.is_a?(self.class) ? value.to_h : value
  end
end