Class: Multicfg

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

Overview

A configuration loaded from multiple sources. TODO: proper rdoc

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(prefix = nil) ⇒ Multicfg

Returns a new instance of Multicfg.



8
9
10
# File 'lib/multicfg.rb', line 8

def initialize(prefix = nil)
  @prefix = prefix
end

Class Method Details

.load(*args) ⇒ Object



59
60
61
# File 'lib/multicfg.rb', line 59

def load(*args)
  args.reduce(new) { |a, e| a.load(e) }
end

.merge(l, r) ⇒ Object



53
54
55
56
57
# File 'lib/multicfg.rb', line 53

def merge(l, r)
  return r unless l.is_a?(Hash) && r.is_a?(Hash)
  r.each { |k, v| l[k] = merge(l[k], v) }
  l
end

Instance Method Details

#filter(hash = {}) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/multicfg.rb', line 40

def filter(hash = {})
  regexp = /^#{@prefix}[_\-]/i if @prefix
  regexp ||= /^/
  hash.each_with_object({}) do |kv, h|
    h[$'.downcase.to_sym] = kv[1] if kv[0] =~ regexp
  end
end

#from_stream(io) ⇒ Object



48
49
50
# File 'lib/multicfg.rb', line 48

def from_stream(io)
  io.read
end

#load(x) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/multicfg.rb', line 16

def load(x)
  case x
  when Pathname then load(x.read)
  when Array    then load(Hash[*x])
  when IO       then load(read(io))
  when String   then load_or_parse(x)
  else               merge(filter(x.to_h))
  end
end

#load_or_parse(s) ⇒ Object



34
35
36
37
38
# File 'lib/multicfg.rb', line 34

def load_or_parse(s)
  pathname = Pathname.new(s)
  return load(pathname) if pathname.readable?
  parse(s)
end

#merge(another) ⇒ Object



12
13
14
# File 'lib/multicfg.rb', line 12

def merge(another)
  self.class.merge(self, another)
end

#parse(s) ⇒ Object



26
27
28
# File 'lib/multicfg.rb', line 26

def parse(s)
  merge(YAML.load(s))
end

#read(io) ⇒ Object



30
31
32
# File 'lib/multicfg.rb', line 30

def read(io)
  YAML.load(io)
end