LoginSignup
0

More than 5 years have passed since last update.

Elixirでコンパイル時にconfigの値をチェックする

Last updated at Posted at 2018-03-16

追記

コメントでafter_compileを使わなくてもよい方法をいただきました。
after_compile版も残しておきますが、ぜひコメントの方をご覧ください。


重要なconfigの値があり、実行時ではなくコンパイル時にチェックし、
おかしければエラーで終了させたかった。

調べた結果、 @after_compile で実現できた。
https://hexdocs.pm/elixir/Module.html#module-after_compile

sample source

defmodule ConfigError do
  defexception [:message]
end

defmodule ConfigCheckEx do
  @after_compile __MODULE__

  def __after_compile__(_env, _bytecode) do
    val = Application.fetch_env!(:config_check, :val)

    unless val in [:hoge, :fuga] do
      raise ConfigError, "val must be :hoge or :fuga"
    end
  end
end

config.exs

use Mix.Config

config :config_check, val: :piyo

実行結果

$ mix compile
Compiling 1 file (.ex)

== Compilation error in file lib/config_check_ex.ex ==
** (ConfigError) val must be :hoge or :fuga
    lib/config_check_ex.ex:12: ConfigCheckEx.__after_compile__/2
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6

もっといい方法があれば知りたい。

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
0