Working with components
OTP applications
For the application to be standalone and start when the beam start, it needs to be an OTP application.
In the mix.exs that was created when creating the project with mix.
defmodule Todo.MixProject do
use Mix.Project
def project do
[
app: :todo,
version: "0.1.0",
elixir: "~> 1.17",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {Todo.Application, []} # This line needs to be added.
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
As well as adding a file in the project lib.
defmodule Todo.Application do
use Application
def start(_, _) do
Todo.System.start_link()
end
end
This is used as a starting point of the application.
After that the application will launch on the project initialization.
Adding a dependency
Adding dependencies to an application is as simple as adding an dependencies in mix.exs
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
These packages can be found in hex.pm
Configuring applications
OTP applications can be configured using an application environement, an in memory key value store where keys are atoms and values are elixir terms.
these resides in elixir scripts, in the config folder. These can be accessed though the Application module.
config/runtime.exs file is an example of a script that evaluate at runtime before the application starts. It is a good place it’s enviroment configuration.
Sometimes it’s good practive to separate configuration for different mix environement for that setting can be chosen like:
http_port =
if config_env() != :test,
do: System.get_env("TODO_HTTP_PORT", "5454"),
else: System.get_env("TODO_TEST_HTTP_PORT", "5455")
It’s best practive to separate, production, test, dev. things like port, database… so they wouldn’t polute and interfere with each other.