LoginSignup
10
6

More than 5 years have passed since last update.

Mix Config - Elixir プロジェクトの設定管理

Posted at

Ruby 脳のおかげで、YAML にでも必要な設定を書こうと思ったら、偉い人がそれはダメって言ってました。

良い感じの config ファイルが既にあるとのこと。使い方の詳しいことはMix.Config を見てもらえればと。

よくわからなかったので、コンソールでちょっとだけいじってみました。Elixir の書き方を知らないので、基本はドキュメントからコピペで動かしてます。

準備:プロジェクトからコンソールを起動

プロジェクトを新規作成して、

% mix new ex
* creating README.md
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/ex.ex
* creating test
* creating test/test_helper.exs
* creating test/ex_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

    cd ex
    mix test

Run "mix help" for more commands.

プロジェクトをコンパイルして、

% mix compile
Compiled lib/ex.ex
Generated ex app
Consolidated List.Chars
Consolidated String.Chars
Consolidated Collectable
Consolidated Enumerable
Consolidated IEx.Info
Consolidated Inspect

コンソールを起動する

iex -S mix

プロジェクトに設定されたすべての設定内容を読み取る

Application.get_all_env を使うと読み込めるらしい。引数にプロジェクト名を表す atom (symbol) を指定するらしい。

iex> Application.get_all_env(:ex)
[included_applications: []]

何も設定していないので、空です。 config/ 以下に実行環境に応じて設定を書くのがお作法みたいです。

設定を追加する

Mix.Config.persist を使うと設定を追加できるみたい。

iex> Mix.Config.persist(ex: [author: :yulii, type: :qiita])
[:ex]
iex> Application.get_all_env(:ex)
[included_applications: [], author: :yulii, type: :qiita]

特定の設定を読み取る

Application.fetch_env すると読み取れるっぽいです。! の取り扱いがよくわかりませんので、両方やってみました。

設定されているキーを読み取る

iex> Application.fetch_env(:ex, :author)  
{:ok, :yulii}
iex> Application.fetch_env!(:ex, :author)
:yulii

設定されていないキーを参照する

iex> Application.fetch_env(:ex, :unknown) 
:error
iex> Application.fetch_env!(:ex, :unknown)
** (ArgumentError) application :ex is not loaded, or the configuration parameter :unknown is not set
    (elixir) lib/application.ex:203: Application.fetch_env!/2

他の使い方を調べる

タブを叩くと候補が出てくるので、適宜ドキュメント見ながら試してみると良さそう。

Application の関数

iex> Application.
app_dir/1                 app_dir/2                 delete_env/3              
ensure_all_started/2      ensure_started/2          fetch_env!/2              
fetch_env/2               format_error/1            get_all_env/1             
get_application/1         get_env/3                 load/1                    
loaded_applications/0     put_env/4                 spec/1                    
spec/2                    start/2                   started_applications/1    
stop/1                    unload/1         

Mix.Config の関数

iex> Mix.Config. 
Agent               LoadError           config/2            
config/3            import_config/1     merge/2             
persist/1           read!/1             read_wildcard!/1    
validate!/1   

Elixir 初めて触ったので、用語とか違ってたらゴメンナサイ。。

10
6
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
10
6