Class: Configus::Config

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

Instance Method Summary collapse

Constructor Details

#initialize(config, section = nil) ⇒ Config

Returns a new instance of Config.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/configus/config.rb', line 5

def initialize(config, section = nil)
  @config = {}
  config.each_pair do |key, value|
    @config[key] = value.is_a?(Hash) ? Config.new(value) : value
  end

  (class << self; self; end).class_eval do
    config.each_pair do |key, value|
      case value
      when Hash
        value = Config.new(value)
      when Proc
        value
      end

      define_method key.to_sym do
        value.is_a?(Proc) ? instance_exec(&value) : value
      end
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &blk) ⇒ Object



44
45
46
# File 'lib/configus/config.rb', line 44

def method_missing(meth, *args, &blk)
  raise "'#{meth}' key does not exist in your configus"
end

Instance Method Details

#[](key) ⇒ Object



27
28
29
# File 'lib/configus/config.rb', line 27

def [](key)
  @config[key]
end

#each_pair(&block) ⇒ Object



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

def each_pair(&block)
  #TODO: hash values should be Configus instance object
  @config.each_pair(&block)
end

#to_hashObject



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

def to_hash
  hash = {}
  @config.each_pair do |key, value|
    hash[key] = value.respond_to?(:to_hash) ? value.to_hash : value
  end
  hash
end