Skip to content

Instantly share code, notes, and snippets.

@daveshah
Created February 11, 2022 14:30
Show Gist options
  • Save daveshah/514c417bdc71e6498a86567bccf36977 to your computer and use it in GitHub Desktop.
Save daveshah/514c417bdc71e6498a86567bccf36977 to your computer and use it in GitHub Desktop.
Quick and dirty Elixir .env file loader
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