Skip to content
Permalink
Browse files

Merge pull request #362 from rossta/feature/add-dotenv-parse

Add Dotenv.parse method
  • Loading branch information...
cadwallion committed Feb 21, 2019
2 parents 80cd968 + f1afe41 commit 6a36885a572d7a5b0a47374433f915d6c0d201c9
Showing with 84 additions and 0 deletions.
  1. +10 −0 README.md
  2. +9 −0 lib/dotenv.rb
  3. +65 −0 spec/dotenv_spec.rb
@@ -177,6 +177,16 @@ Dotenv.require_keys("SERVICE_APP_ID", "SERVICE_KEY", "SERVICE_SECRET")

If any of the configuration keys above are not set, your application will raise an error during initialization. This method is preferred because it prevents runtime errors in a production application due to improper configuration.

### Parsing

To parse a list of env files for programmatic inspection without modifying the ENV:

```ruby
Dotenv.parse(".env.local", ".env")
# => {'S3_BUCKET' => 'YOURS3BUCKET', 'SECRET_KEY' => 'YOURSECRETKEYGOESHERE', ...}
```

This method returns a hash of the ENV var name/value pairs.

## Frequently Answered Questions

@@ -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.
@@ -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") }

0 comments on commit 6a36885

Please sign in to comment.
You can’t perform that action at this time.