public
Description: Provides a way to manage environment specific configuration settings.
Homepage:
Clone URL: git://github.com/UnderpantsGnome/config_reader-gem.git
config_reader-gem / lib / config_reader.rb
100644 75 lines (60 sloc) 1.478 kb
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
require 'yaml'
begin
  require 'erb'
rescue LoadError
  puts "ERB not found, you won't be able to use ERB in your config"
end
 
$:.unshift(File.dirname(__FILE__)) unless
  $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
 
class ConfigReader
  @config_file = nil
  @config = nil
 
  class << self
    def config
      @config = nil unless defined?(@config)
      @config ||= reload
    end
 
    def config_file=(file)
      @config_file = file
    end
 
    def reload
      raise 'No config file set' unless @config_file
 
      if defined?(ERB)
        conf = YAML.load(ERB.new(File.open(find_config).read).result)
      else
        conf = YAML.load(File.open(find_config).read)
      end
 
      raise 'No config found' unless conf
 
      if defined?(RAILS_ENV)
        env = RAILS_ENV
      elsif defined?(APP_ENV)
        env = APP_ENV
      end
 
      _conf = conf['defaults']
      _conf.merge!(conf[env]) if conf[env]
      _conf
    end
 
    def [](key)
      config[key]
    end
 
    def find_config
      return @config_file if File.exist?(@config_file)
 
      %w( . config ).each do |dir|
        config_file = File.join(dir, @config_file)
        return config_file if File.exist?(config_file)
      end
      ''
    end
 
    def method_missing(key)
      config[key.to_s] || super
    end
 
    def inspect
      puts config.inspect
    end
  end
end
 
class Hash
  def method_missing(key)
    self[key.to_s] || super
  end
end