Project

General

Profile

Download (2.16 KB) Statistics
| Branch: | Tag: | Revision:

root / lib / cyborghood / config.rb @ 44648f83

1
#--
2
# CyborgHood, a distributed system management software.
3
# Copyright (c) 2009 Marc Dequènes (Duck) <Duck@DuckCorp.org>
4
#
5
# This program is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation, either version 3 of the License, or
8
# (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
#++
18

    
19
require 'singleton'
20
require 'yaml'
21
require "cyborghood/config_setup"
22

    
23
module CyborgHood
24
  class Config
25
    include Singleton
26

    
27
    CONFFILE_GLOBAL = "cyborghood.conf"
28
    CONFFILE_BOT = "cyborghood_%s.conf"
29

    
30
    def self.load(name = nil)
31
      # load all config parts
32
      config = fetch_config
33
      unless name.nil?
34
        config_spc = fetch_config(name)
35
        config = merge_configs(config, config_spc) if config_spc
36
      end
37

    
38
      # create config object for easier access
39
      @@config = config.to_ostruct.freeze
40
    end
41

    
42
    def method_missing(sym, *args, &block)
43
      begin
44
        @@config.send sym, *args, &block
45
      rescue
46
        nil
47
      end
48
    end
49

    
50
    private
51

    
52
    def self.fetch_config(name = nil)
53
      begin
54
        if name.nil?
55
          filename = CONFFILE_GLOBAL
56
        else
57
          filename = sprintf(CONFFILE_BOT, name)
58
        end
59
        filepath = File.join(File.expand_path(CFG_DIR), filename)
60
        str = File.read(filepath)
61
        YAML.load(str)
62
      rescue
63
        logger.fatal "Problems fetching configuration file '" + filepath + "': " + $!
64
        exit 1
65
      end
66
    end
67

    
68
    def self.merge_configs(conf1, conf2)
69
      new_conf = conf1.dup
70
      conf2.each_pair do |k, v|
71
        if conf1.has_key?(k) and conf1[k].is_a?(Hash) and v.is_a?(Hash)
72
          new_conf[k] = merge_configs(conf1[k], v)
73
        else
74
          new_conf[k] = v
75
        end
76
      end
77
      return new_conf
78
    end
79
  end
80
end
(1-1/12)