Skip to content

Commit

Permalink
Merge pull request #354 from dmitry-ilyashevich/master
Browse files Browse the repository at this point in the history
Added require keys method to raise if not defined
  • Loading branch information
Andrew Nordman authored Sep 23, 2018
2 parents 25a7a5c + 2b3b59c commit 879af5e
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,21 @@ SECRET_KEY=YOURSECRETKEYGOESHERE # comment
SECRET_HASH="something-with-a-#-hash"
```

### Required Keys

If a particular configuration value is required but not set, it's appropriate to raise an error.

To require configuration keys:

```ruby
# config/initializers/dotenv.rb

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.


## Frequently Answered Questions

### Can I use dotenv in production?
Expand Down
7 changes: 7 additions & 0 deletions lib/dotenv.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require "dotenv/parser"
require "dotenv/environment"
require "dotenv/missing_keys"

# The top level Dotenv module. The entrypoint for the application logic.
module Dotenv
Expand Down Expand Up @@ -63,6 +64,12 @@ def instrument(name, payload = {}, &block)
end
end

def require_keys(*keys)
missing_keys = keys.flatten - ::ENV.keys
return if missing_keys.empty?
raise MissingKeys, missing_keys
end

def ignoring_nonexistent_files
yield
rescue Errno::ENOENT
Expand Down
10 changes: 10 additions & 0 deletions lib/dotenv/missing_keys.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module Dotenv
class Error < StandardError; end

class MissingKeys < Error # :nodoc:
def initialize(keys)
key_word = "key#{keys.size > 1 ? 's' : ''}"
super("Missing required configuration #{key_word}: #{keys.inspect}")
end
end
end
14 changes: 14 additions & 0 deletions spec/dotenv_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,20 @@
end
end

describe "require keys" do
let(:env_files) { [".env", fixture_path("bom.env")] }

before { Dotenv.load(*env_files) }

it "raises exception with not defined mandatory ENV keys" do
expect { Dotenv.require_keys("BOM", "TEST") }.to \
raise_error(
Dotenv::MissingKeys,
'Missing required configuration key: ["TEST"]'
)
end
end

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

Expand Down

0 comments on commit 879af5e

Please sign in to comment.