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
|
# File 'lib/rails_config/settings.rb', line 10
def self.load(options={})
raise "options must contain :source_dir" unless options[:source_dir]
opts={
log_debug: false,
environment: 'development',
output_file: nil
}.merge(options)
puts "[#{self.name}] Loading application settings from files in #{opts[:source_dir]}" if opts[:log_debug]
setting_files=Dir.glob(File.join(opts[:source_dir], '*.yml')).map { |p| File.new(p) }.inject({}) { |h, f| h[File.basename(f).downcase.split(/(.*)[.]yml/).join]=f; h }
settings=Hash.new
setting_files.each_pair do |key, file|
puts "[#{self.name}] Loading #{key} settings from file #{file.path}" if opts[:log_debug]
settings[key]=YAML.load_file(file)[opts[:environment]]
if (env=YAML.load_file(file)['env'])
env.keys.each do |k|
if (env_var=ENV[k.to_s.upcase])
value=env[k]['with'] || :to_s
value=[value] unless value.is_a?(Array)
value=value.inject(env_var) { |v, m| eval("v.#{m}") }
value_hash=(env[k]['to'] || k.downcase.slice("#{File.basename(file)}_")).split('/').reverse.reduce(value) { |r, e| {e => r} }
settings[key].deep_merge!(value_hash)
end
end
end
end
if opts[:output_file]
hash=settings.deep_stringify_keys
method=hash.respond_to?(:ya2yaml) ? :ya2yaml : :to_yaml
yaml_string=hash.deep_stringify_keys.send(method)
yaml_string.gsub("!ruby/symbol ", ":").sub("---", "").split("\n").map(&:rstrip).join("\n").strip
begin
File.open(opts[:output_file], 'w') do |f|
puts "[#{self.name}] Writing application settings to #{f.path}" if opts[:log_debug]
f.write(yaml_string)
f.close
end
rescue Exception => ex
puts ex.message
puts ex.backtrace.join("\n")
end
end
RecursiveOpenStruct.new(settings)
end
|