Last active
July 28, 2022 14:14
-
-
Save alissonfpmorais/d1fdc6e0332673ddd10f32620c2de0d0 to your computer and use it in GitHub Desktop.
Environment file loader for elixir projects
This file contains 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
import Config | |
defmodule EnvFile do | |
@moduledoc """ | |
This module may load environment files (commonly ".env") | |
into PID's environment. | |
After loading a file, all variables may be accessed using | |
&System.get_env/0 or &System.get_env/2 | |
For instance, imagine a .env file in your project's root directory like: | |
-------- .env | |
# My special env var | |
HELLO=WORLD | |
-------- | |
In your dev.exs you can do: | |
-------- dev.exs | |
# File containing this module | |
import_config "env_loader.exs" | |
# outputs "WORLD" | |
"HELLO" | |
|> System.get_env() | |
|> IO.inspect() | |
-------- | |
Simple as that :) | |
""" | |
@line_break "\n" | |
def load(file_path) when is_binary(file_path) do | |
case File.read(file_path) do | |
{:error, _reason} -> | |
raise """ | |
Can't load env file! | |
Some common reasons are: | |
1) File is not in the right path; | |
2) File name is mispelled; | |
3) Syntax are incorrectly. | |
""" | |
{:ok, file} -> | |
file | |
|> parse() | |
|> System.put_env() | |
end | |
end | |
defp parse(file) when is_binary(file) do | |
file | |
|> String.split(@line_break) | |
|> Enum.map(&String.trim_leading/1) | |
|> Enum.filter(¬_empty?/1) | |
|> Enum.filter(¬_commentted/1) | |
|> Enum.map(&key_value/1) | |
end | |
defp empty?(text), do: text == "" | |
defp not_empty?(text), do: not empty?(text) | |
defp commentted(text), do: String.at(text, 0) == "#" | |
defp not_commentted(text), do: not commentted(text) | |
defp key_value(text) do | |
text | |
|> String.split("=", parts: 2) | |
|> List.to_tuple() | |
end | |
end | |
EnvFile.load(".env") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment