Hello, Mix!

Mixとは

Elixirのプロジェクト管理ツールです。

プロジェクトの作成

$ mix new hello_world

* creating README.md
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/hello_world.ex
* creating test
* creating test/test_helper.exs
* creating test/hello_world_test.exs

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

    cd hello_world
    mix test

Run "mix help" for more commands.
  • README.md
    • プロジェクトの説明
  • .gitignore
    • gitの管理下に置かないファイルの定義
  • mix.exs
    • プロジェクトの設定
  • config/*
    • アプリケーションの設定
  • lib/*
    • ライブラリ
  • test/*

メインモジュールの作成

プロジェクトが作成されたので、プロジェクトのディレクリに移動してビルドしてみます。

$ cd hello_world
$ mix escript.build

Compiled lib/hello_world.ex
Generated hello_world app
Consolidated List.Chars
Consolidated Collectable
Consolidated String.Chars
Consolidated Enumerable
Consolidated IEx.Info
Consolidated Inspect
** (Mix) Could not generate escript, please set :main_module in your project configuration (under :escript option) to a module that implements main/1

「プロジェクト設定の:escriptオプションにmain関数を実装している:main_moduleを指定しろ」 とのことなので、そのようにします。

# ./mix.exs

defmodule HelloWorld.Mixfile do
  use Mix.Project

  def project do
    [app: :hello_world,
     version: "0.0.1",
     elixir: "~> 1.2-rc",
     build_embedded: Mix.env == :prod,
     start_permanent: Mix.env == :prod,
     deps: deps]
  end

  # ... 以下略
end
# ./lib/hello_world.exs

defmodule HelloWorld do

  def main(args) do
    IO.puts "Hello, World!!"
  end

end

ビルド&実行

メインモジュールを追記後、再度ビルドします。

$ cd hello_world
$ mix escript.build

Compiled lib/hello_world.ex
Generated hello_world app
Consolidated List.Chars
Consolidated Collectable
Consolidated String.Chars
Consolidated Enumerable
Consolidated IEx.Info
Consolidated Inspect
Generated escript hello_world with MIX_ENV=dev

ビルドに成功すると直下にバイナリが作成されるので実行してみます。

$ ./hello_world

Hello, world!

Programming Elixir: Functional, Concurrent, Pragmatic, Fun

Programming Elixir: Functional, Concurrent, Pragmatic, Fun