1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Elixir | Mix | Environments #elixir

Posted at

Elixir | Mix | Environments #elixir

概要

Elixir に付属している CLI Tool Mix は Environments をサポートしています。

Environments

デフォルトでは

  • dev :mix compile の実行時など
  • test :mix test の実行時など
  • prd :本番環境

が用意されています。
環境変数 MIX_ENV を設定すると、その内容を Mix.env で取得できます。

Mix.env

デフォルトではすべての環境が同じ設定になっています。
個別の環境情報を設定するには、 mix.exs の中で
Mix.env を参照して設定を行う必要があります。

サンプル

プロジェクトのひな型生成

$ mix new mix_env
* creating README.md
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/mix_env.ex
* creating test
* creating test/test_helper.exs
* creating test/mix_env_test.exs
$ tree
.
`-- mix_env
    |-- config
    |   `-- config.exs
    |-- lib
    |   `-- mix_env.ex
    |-- mix.exs
    |-- README.md
    `-- test
        |-- mix_env_test.exs
        `-- test_helper.exs

mix.exs の設定

defmodule MixEnv.Mixfile do
  use Mix.Project

  def project do
    [app: :mix_env,
     version: "0.0.1",
     elixir: "~> 1.0.0",
     deps: deps,
     output_env: output_env(Mix.env)]
  end

  def application do
    [applications: [:logger]]
  end

  defp deps do
    []
  end

  defp output_env(:prod), do: IO.puts "prod"
  defp output_env(:test), do: IO.puts "test"
  defp output_env(:dev), do: IO.puts "dev"
end

env の動作確認

$ mix test
1dev
test
Compiled lib/mix_env.ex
Generated mix_env.app
.

Finished in 0.03 seconds (0.03s on load, 0.00s on tests)
1 tests, 0 failures

Randomized with seed 761300
vagrant@precise64:~/hoge/sample/mix_env/mix_env$ mix compile
dev
Compiled lib/mix_env.ex
Generated mix_env.app
vagrant@precise64:~/hoge/sample/mix_env/mix_env$ mix run -e "MixEnv"
dev
vagrant@precise64:~/hoge/sample/mix_env/mix_env$ mix run -e "IO.puts :hoge"
dev
hoge
$ MIX_ENV=prod mix compile
warning: the VM is running with native name encoding of latin1 which may cause Elixir to malfunction as it expects utf8. Please ensure your locale is set to UTF-8 (which can be verified by running "locale" in your shell)
prod
Compiled lib/mix_env.ex
Generated mix_env.app

参照

Elixir Official | Mix | Environments

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?