retr0h (owner)

Fork Of

Revisions

gist: 179886 Download_button fork
public
Public Clone URL: git://gist.github.com/179886.git
Embed All Files: show embed
Ruby #
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
::AppConfig = ApplicationConfiguration.new("main.yml", "main_local.yml")
AppConfig.use_environment!(Rails.env)
 
## main.yml
  defaults: &defaults
    one: won
    two: too
    web_service:
      url: http://foo
      port: 80
 
  development:
    <<: *defaults
 
## main_local.yml
  web_service:
    port: 8080
 
 
 
#### My app_config lib
 
class AppConfiguration
  class << self
    CONFIG_BASE = File.join(RAILS_ROOT, 'config', 'app_config')
 
    def app_config_configuration(environment)
      configs = load_config_file(app_config_configuration_file)
      hashes = [configs['default'], configs[environment]]
 
      begin
        local_config = load_config_file(app_config_override_file)
        hashes << local_config
      rescue
        nil ### local config optional.
      end
 
      hashes.compact!
      hashes.inject({}){|aggregate,current| recursive_merge(aggregate, current)}
    end
 
  protected
    def load_config_file(file)
      YAML::load(ERB.new(IO.read(file)).result(binding))
    rescue => e
      raise "ERROR: loading '#{file}': #{e}"
    end
 
    def app_config_configuration_file
      "#{CONFIG_BASE}.yml"
    end
 
    def app_config_override_file
      "#{CONFIG_BASE}_local.yml"
    end
 
    ##
    # Taken from http://github.com/cjbottaro/app_config/tree/master
    def recursive_merge(h1, h2)
      h1.merge(h2){|k, v1, v2| v2.kind_of?(Hash) ? recursive_merge(v1, v2) : v2}
    end
  end
end