Class: TrakFlow::ConfigSection

Inherits:
Object
  • Object
show all
Defined in:
lib/trak_flow/config/section.rb

Overview

ConfigSection provides method access to nested configuration hashes

Examples:

section = ConfigSection.new(host: 'localhost', port: 5432)
section.host  # => 'localhost'
section.port  # => 5432

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ ConfigSection



12
13
14
15
16
17
# File 'lib/trak_flow/config/section.rb', line 12

def initialize(hash = {})
  @data = {}
  (hash || {}).each do |key, value|
    @data[key.to_sym] = value.is_a?(Hash) ? ConfigSection.new(value) : value
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/trak_flow/config/section.rb', line 19

def method_missing(method, *args, &)
  key = method.to_s
  if key.end_with?('=')
    @data[key.chomp('=').to_sym] = args.first
  elsif @data.key?(method)
    @data[method]
  end
end

Instance Method Details

#[](key) ⇒ Object



39
40
41
# File 'lib/trak_flow/config/section.rb', line 39

def [](key)
  @data[key.to_sym]
end

#[]=(key, value) ⇒ Object



43
44
45
# File 'lib/trak_flow/config/section.rb', line 43

def []=(key, value)
  @data[key.to_sym] = value
end

#eachObject



56
57
58
# File 'lib/trak_flow/config/section.rb', line 56

def each(&)
  @data.each(&)
end

#keysObject



52
53
54
# File 'lib/trak_flow/config/section.rb', line 52

def keys
  @data.keys
end

#merge(other) ⇒ Object



47
48
49
50
# File 'lib/trak_flow/config/section.rb', line 47

def merge(other)
  other_hash = other.is_a?(ConfigSection) ? other.to_h : other
  ConfigSection.new(deep_merge(to_h, other_hash || {}))
end

#respond_to_missing?(method, include_private = false) ⇒ Boolean



28
29
30
31
# File 'lib/trak_flow/config/section.rb', line 28

def respond_to_missing?(method, include_private = false)
  key = method.to_s.chomp('=').to_sym
  @data.key?(key) || super
end

#to_hObject



33
34
35
36
37
# File 'lib/trak_flow/config/section.rb', line 33

def to_h
  @data.transform_values do |v|
    v.is_a?(ConfigSection) ? v.to_h : v
  end
end