class RailsConfig::Settings
Public Class Methods
load(options={})
click to toggle source
# File lib/rails_config/settings.rb, line 10 def self.load(options={}) # sorry, you must supply the source_dir raise "options must contain :source_dir" unless options[:source_dir] opts={ log_debug: false, #source_dir: File.expand_path("..", __FILE__), environment: 'development', output_file: nil }.merge(options) # Load various settings files 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 # Write out the loaded settings if an output file is specified 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