Elixir Schoolの勉強メモです。
はじめに
Elixirで実行ファイルをビルドするにはescriptを利用する。
escriptはErlangがインストールされているあらゆるシステム上で動作する実行ファイルを生み出します。
実行ファイルのエントリポイント(最初に実行する位置)として扱うモジュールまでを作成する。
まずはmixでプロジェクトを作成する。
$ mix new hello
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.exs
* creating lib
* creating lib/hello.ex
* creating test
* creating test/test_helper.exs
* creating test/hello_test.exs
Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:
cd hello
mix test
作成したらhelloディレクトリに移動する。
lib/cli.exs
ファイルを作成する。
lib/cli.exs
defmodule Hello.CLI do
def main(args \\ []) do
# Do stuff
end
end
次にMixfileを更新する。
:main_module
を一緒に指定した:escript
オプションをプロジェクトに組み込む。
mix.exs
defmodule Hello.MixProject do
use Mix.Project
def project do
[app: :hello, version: "0.0.1", escript: escript()]
end
defp escript do
[main_module: Hello.CLI]
end
end
引数の解析
アプリケーションのセットアップが終わったら、コマンドライン引数の解析へ移る。
OptionPerser.perse/2
と:switches
オプションを用いて、フラグが真理値であることを示す。
lib/cli.exs
defmodule Hello.CLI do
def main(args \\ []) do
args
|> parse_args
|> response
|> IO.puts()
end
defp parse_args(args) do
{opts, word, _} =
args
|> OptionParser.parse(switches: [upcase: :boolean])
{opts, List.to_string(word)}
end
defp response({opts, word}) do
if opts[:upcase], do: String.upcase(word), else: word
end
end
ビルド
実行ファイルのビルドをします。
$ mix escript.build
Generated hello app
Generated escript hello with MIX_ENV=dev
試しに実行してみる。
$ ./hello --upcase Hello
HELLO
$ ./hello Hi
Hi