Merge pull request #103 from csquared/load_env_from_irb

Load env from irb
This commit is contained in:
David Dollar
2011-12-05 12:37:05 -08:00
3 changed files with 60 additions and 19 deletions

View File

@@ -4,5 +4,10 @@ module Foreman
class AppDoesNotExist < Exception; end
# load contents of env_file into ENV
def self.load_env!(env_file = './.env')
require 'foreman/engine'
Foreman::Engine.load_env!(env_file)
end
end

View File

@@ -12,7 +12,6 @@ class Foreman::Engine
attr_reader :procfile
attr_reader :directory
attr_reader :environment
attr_reader :options
extend Term::ANSIColor
@@ -26,6 +25,11 @@ class Foreman::Engine
@environment = read_environment_files(options[:env])
end
def self.load_env!(env_file)
@environment = read_environment_files(env_file)
apply_environment!
end
def start
proctitle "ruby: foreman master"
termtitle "#{File.basename(@directory)} - foreman (#{processes.size} processes)"
@@ -73,7 +77,7 @@ private ######################################################################
end
def fork_individual(process, num, port)
@environment.each { |k,v| ENV[k] = v }
apply_environment!
ENV["PORT"] = port.to_s
ENV["PS"] = "#{process.name}.#{num}"
@@ -175,27 +179,37 @@ private ######################################################################
@current_color >= COLORS.length ? "" : COLORS[@current_color]
end
def read_environment_files(filenames)
environment = {}
module Env
attr_reader :environment
(filenames || "").split(",").map(&:strip).each do |filename|
error "No such file: #{filename}" unless File.exists?(filename)
environment.merge!(read_environment(filename))
end
def read_environment_files(filenames)
environment = {}
environment.merge!(read_environment(".env")) unless filenames
environment
end
def read_environment(filename)
return {} unless File.exists?(filename)
File.read(filename).split("\n").inject({}) do |hash, line|
if line =~ /\A([A-Za-z_0-9]+)=(.*)\z/
hash[$1] = $2
(filenames || "").split(",").map(&:strip).each do |filename|
error "No such file: #{filename}" unless File.exists?(filename)
environment.merge!(read_environment(filename))
end
hash
environment.merge!(read_environment(".env")) unless filenames
environment
end
def read_environment(filename)
return {} unless File.exists?(filename)
File.read(filename).split("\n").inject({}) do |hash, line|
if line =~ /\A([A-Za-z_0-9]+)=(.*)\z/
hash[$1] = $2
end
hash
end
end
def apply_environment!
@environment.each { |k,v| ENV[k] = v }
end
end
include Env
extend Env
end

View File

@@ -8,4 +8,26 @@ describe Foreman do
it { should be_a String }
end
describe "::load_env!(env_file)" do
before do
FakeFS.activate!
end
after do
FakeFS.deactivate!
ENV['FOO'] = nil
end
it "should load env_file into ENV" do
File.open("/tmp/env1", "w") { |f| f.puts("FOO=bar") }
Foreman.load_env!("/tmp/env1")
ENV['FOO'].should == 'bar'
end
it "should assume env_file in ./.env" do
File.open("./.env", "w") { |f| f.puts("FOO=bar") }
Foreman.load_env!
ENV['FOO'].should == 'bar'
end
end
end