Class: RailsConfig::Environment

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/rails_config/environment.rb

Class Method Summary collapse

Class Method Details

.load(options = {}) ⇒ Object



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
# File 'lib/rails_config/environment.rb', line 9

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__),
    keys: ['application', 'development'],
    output_file: nil
  }.merge(options)

  # Load various environment files
  puts "[#{self.name}] Loading application environment from files in #{opts[:source_dir]}" if opts[:log_debug]
  opts[:keys].each do |key|
    env_file=File.join(opts[:source_dir], "#{key}.env")
    if File.exist?(env_file)
      puts "[#{self.name}] Loading environment file #{env_file}" if opts[:log_debug]
      File.new(env_file).each do |line|
        if (m=/^\s*([A-Za-z0-9_-]+)=(.+)\s*$/.match(line))
          ENV[m[1]]=m[2]
        end
      end
    end
  end

  # Write out the loaded environment if an output file is specified
  if opts[:output_file]
    env_string=ENV.to_hash.map { |k, v| "#{k}=#{v}\n" }.join
    begin
      File.open(opts[:output_file], 'w') do |f|
        puts "[#{self.name}] Writing application environment to #{f.path}" if opts[:log_debug]
        f.write(env_string)
        f.close
      end
    rescue Exception => ex
      puts ex.message
      puts ex.backtrace.join("\n")
    end
  end

  ENV.to_hash

end