Skip to content

Commit

Permalink
Add Dotenv.parse method
Browse files Browse the repository at this point in the history
Exposes parsing logic as a public API to allow programmatic inspection
of .env files without modifying ENV.

One such use case is for automated application setup to
create/read/modify .env files prior to running the application for the
first time.
  • Loading branch information
rossta committed Nov 9, 2018
1 parent d749366 commit a3f8d16
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/dotenv.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ def overload!(*filenames)
end
end

# returns a hash of parsed key/value pairs but does not modify ENV
def parse(*filenames)
with(*filenames) do |f|
ignoring_nonexistent_files do
Environment.new(f, false)
end
end
end

# Internal: Helper to expand list of filenames.
#
# Returns a hash of all the loaded environment variables.
Expand Down
65 changes: 65 additions & 0 deletions spec/dotenv_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,71 @@
end
end

describe "parse" do
let(:env_files) { [] }
subject { Dotenv.parse(*env_files) }

context "with no args" do
let(:env_files) { [] }

it "defaults to .env" do
expect(Dotenv::Environment).to receive(:new).with(expand(".env"),
anything)
subject
end
end

context "with a tilde path" do
let(:env_files) { ["~/.env"] }

it "expands the path" do
expected = expand("~/.env")
allow(File).to receive(:exist?) { |arg| arg == expected }
expect(Dotenv::Environment).to receive(:new).with(expected, anything)
subject
end
end

context "with multiple files" do
let(:env_files) { [".env", fixture_path("plain.env")] }

let(:expected) do
{ "OPTION_A" => "1",
"OPTION_B" => "2",
"OPTION_C" => "3",
"OPTION_D" => "4",
"OPTION_E" => "5",
"PLAIN" => "true",
"DOTENV" => "true" }
end

it "does not modify ENV" do
subject
expected.each do |key, _value|
expect(ENV[key]).to be_nil
end
end

it "returns hash of parsed key/value pairs" do
expect(subject).to eq(expected)
end
end

it "initializes the Environment with a falsey is_load" do
expect(Dotenv::Environment).to receive(:new).with(anything, false)
subject
end

context "when the file does not exist" do
let(:env_files) { [".env_does_not_exist"] }

it "fails silently" do
expect { subject }.not_to raise_error
expect(subject).to eq({})
end
end
end

describe "Unicode" do
subject { fixture_path("bom.env") }

Expand Down

0 comments on commit a3f8d16

Please sign in to comment.