Class: Konf

Inherits:
Hash
  • Object
show all
Defined in:
lib/konf.rb

Defined Under Namespace

Classes: Invalid, NotFound

Instance Method Summary collapse

Constructor Details

#initialize(source, root = nil) ⇒ Konf

Returns a new instance of Konf.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/konf.rb', line 8

def initialize(source, root = nil)
  hash = case source
  when Hash
    source
  else
    if File.exists?(source.to_s) && yaml = YAML.load(ERB.new(File.read(source.to_s)).result)
      yaml.to_hash
    else
      raise Invalid, "Invalid configuration input: #{source}"
    end
  end
  if root
    hash = hash[root] or raise NotFound, "No configuration found for '#{root}'"
  end
  self.replace hash
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/konf.rb', line 25

def method_missing(name, *args, &block)
  key = name.to_s
  if key.gsub!(/\?$/, '')
    has_key? key
  else
    raise NotFound, "No configuration found for '#{name}'" unless has_key?(key)
    value = fetch key
    value.is_a?(Hash) ? Konf.new(value) : value
  end
end