Class: ConfigX::Config

Inherits:
OpenStruct
  • Object
show all
Defined in:
lib/config_x/config.rb

Instance Method Summary collapse

Constructor Details

#initialize(members) ⇒ Config

Returns a new instance of Config.



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

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_hObject



38
39
40
41
42
# File 'lib/config_x/config.rb', line 38

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

#with_fallback(fallback) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/config_x/config.rb', line 30

def with_fallback(fallback)
  DeepMerge.deep_merge!(
    to_h,
    fallback.to_h,
    overwrite_arrays: true
  ).then { Config.new(_1) }
end