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

Returns a new instance of 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, &block) ⇒ Object



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

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

Instance Method Details

#[](key) ⇒ Object



41
42
43
# File 'lib/trak_flow/config/section.rb', line 41

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

#[]=(key, value) ⇒ Object



45
46
47
# File 'lib/trak_flow/config/section.rb', line 45

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

#each(&block) ⇒ Object



58
59
60
# File 'lib/trak_flow/config/section.rb', line 58

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

#keysObject



54
55
56
# File 'lib/trak_flow/config/section.rb', line 54

def keys
  @data.keys
end

#merge(other) ⇒ Object



49
50
51
52
# File 'lib/trak_flow/config/section.rb', line 49

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

Returns:

  • (Boolean)


30
31
32
33
# File 'lib/trak_flow/config/section.rb', line 30

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

#to_hObject



35
36
37
38
39
# File 'lib/trak_flow/config/section.rb', line 35

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