1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class ConfigFile
  attr_accessor :file, :environment
  
  def initialize(file, environment)
    @file, @environment = file, environment
  end
  
  def [](key)
    config[key]
  end
  
  def needs_reload?
    @configs.nil? || (File.mtime(file) > @mtime)
  end
  
  def ==(other)
    self.config == other.config
  end
  
  def reload
    @mtime   = File.mtime(file)
    @configs = YAML.load(File.read(file)).with_indifferent_access
  end
  
  def config(which=environment)
    reload if needs_reload?
    case which.to_sym
    when :defaults
      (@configs[:defaults] || {}).with_indifferent_access
    else
      case value = @configs[which]
      when Hash
        config(:defaults).merge(value)
      when String
        config(:defaults).merge(config(value))
      else
        config(:defaults)
      end
    end
  end
end