]> CyberLeo.Net >> Repos - CDN/status.git/blob - lib/configuration.rb
And behold, thus she sprang, fully formed, from the head of her progenitor.
[CDN/status.git] / lib / configuration.rb
1 require 'yaml'
2
3 class Configuration
4   include Enumerable
5
6   @@config_path = File.expand_path(File.join(File.dirname(__FILE__), '..', 'etc'))
7
8   def initialize(name)
9     @config_name = name
10   end
11
12   def config_file
13     File.join(@@config_path, @config_name)
14   end
15
16   def load_config
17     STDERR.puts "Reloading configuration"
18     @config_hash = indifferent_params(YAML::load(File.open(config_file)))
19     @config_time = File.stat(config_file).mtime
20   end
21
22   def stale?
23     File.stat(config_file).mtime != @config_time
24   end
25
26   def config_hash
27     load_config if !@config_hash || stale?
28     @config_hash
29   end
30
31   def each(*args, &block)
32     config_hash.each(*args, &block)
33   end
34
35   def [](key)
36     config_hash[key]
37   end
38
39   def indifferent_hash
40     Hash.new {|hash,key| hash[key.to_s] if Symbol === key }
41   end
42
43   def indifferent_params(object)
44     case object
45       when Hash
46         new_hash = indifferent_hash
47         object.each {|key, value| new_hash[key] = indifferent_params(value) }
48         new_hash
49       when Array
50         object.map {|item| indifferent_params(item) }
51       else
52         object
53     end
54   end
55
56   def self.load(name)
57     new(name)
58   end
59 end