LoginSignup
8
0

More than 1 year has passed since last update.

今日のElixirSchoolメモ19「実行ファイル」

Posted at

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
8
0
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
8
0