Skip to content

Commit

Permalink
Add support for a default value in System.get_env
Browse files Browse the repository at this point in the history
  • Loading branch information
guilleiguaran committed Mar 16, 2019
1 parent 94c2ffa commit 07b2c94
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
15 changes: 10 additions & 5 deletions lib/elixir/lib/system.ex
Expand Up @@ -427,8 +427,8 @@ defmodule System do
Returns the value of the given environment variable.
The returned value of the environment variable
`varname` is a string, or `nil` if the environment
variable is not set.
`varname` is a string. If the environment variable
is undefined, returns default (or `nil` if not provided)
## Examples
Expand All @@ -438,11 +438,16 @@ defmodule System do
iex> System.get_env("NOT_SET")
nil
iex> System.get_env("NOT_SET", "4001")
"4001"
"""
@spec get_env(String.t()) :: String.t() | nil
def get_env(varname) when is_binary(varname) do
@spec get_env(String.t(), String.t() | nil) :: String.t() | nil
def get_env(varname, default \\ nil)
when is_binary(varname) and
(is_binary(default) or is_nil(default)) do
case :os.getenv(String.to_charlist(varname)) do
false -> nil
false -> default
other -> List.to_string(other)
end
end
Expand Down
1 change: 1 addition & 0 deletions lib/elixir/test/elixir/system_test.exs
Expand Up @@ -52,6 +52,7 @@ defmodule SystemTest do

test "*_env/*" do
assert System.get_env(@test_var) == nil
assert System.get_env(@test_var, "SAMPLE") == "SAMPLE"
assert System.fetch_env(@test_var) == :error

message = "could not fetch environment variable #{inspect(@test_var)} because it is not set"
Expand Down

0 comments on commit 07b2c94

Please sign in to comment.