Created
February 11, 2022 14:30
-
-
Save daveshah/514c417bdc71e6498a86567bccf36977 to your computer and use it in GitHub Desktop.
Quick and dirty Elixir .env file loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule EnvLoader do | |
def load_env_file!, do: get_env_file() |> set_file_env_vars() | |
defp set_file_env_vars(nil), do: :ok | |
defp set_file_env_vars(file_name) do | |
File.read!(file_name) | |
|> String.split() | |
|> Enum.map(fn kvp -> String.split(kvp, "=") |> List.to_tuple() end) | |
|> System.put_env() | |
end | |
defp get_env_file do | |
File.ls!() | |
|> Enum.find(fn file_name -> | |
case Mix.env() do | |
:prod -> String.equivalent?(file_name, ".env") | |
env -> String.equivalent?(file_name, ".env.#{env}") | |
end | |
end) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment